File size: 9,898 Bytes
88f3fce |
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 |
import path from "path";
import fs from "fs";
import puppeteer from "puppeteer";
import VMind, { ChartType, DataTable } from "@visactor/vmind";
import { isString } from "@visactor/vutils";
enum AlgorithmType {
OverallTrending = "overallTrend",
AbnormalTrend = "abnormalTrend",
PearsonCorrelation = "pearsonCorrelation",
SpearmanCorrelation = "spearmanCorrelation",
ExtremeValue = "extremeValue",
MajorityValue = "majorityValue",
StatisticsAbnormal = "statisticsAbnormal",
StatisticsBase = "statisticsBase",
DbscanOutlier = "dbscanOutlier",
LOFOutlier = "lofOutlier",
TurningPoint = "turningPoint",
PageHinkley = "pageHinkley",
DifferenceOutlier = "differenceOutlier",
Volatility = "volatility",
}
const getBase64 = async (spec: any, width?: number, height?: number) => {
spec.animation = false;
width && (spec.width = width);
height && (spec.height = height);
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(getHtmlVChart(spec, width, height));
const dataUrl = await page.evaluate(() => {
const canvas: any = document
.getElementById("chart-container")
?.querySelector("canvas");
return canvas?.toDataURL("image/png");
});
const base64Data = dataUrl.replace(/^data:image\/png;base64,/, "");
await browser.close();
return Buffer.from(base64Data, "base64");
};
const serializeSpec = (spec: any) => {
return JSON.stringify(spec, (key, value) => {
if (typeof value === "function") {
const funcStr = value
.toString()
.replace(/(\r\n|\n|\r)/gm, "")
.replace(/\s+/g, " ");
return `__FUNCTION__${funcStr}`;
}
return value;
});
};
function getHtmlVChart(spec: any, width?: number, height?: number) {
return `<!DOCTYPE html>
<html>
<head>
<title>VChart Demo</title>
<script src="https://unpkg.com/@visactor/vchart/build/index.min.js"></script>
</head>
<body>
<div id="chart-container" style="width: ${
width ? `${width}px` : "100%"
}; height: ${height ? `${height}px` : "100%"};"></div>
<script>
// parse spec with function
function parseSpec(stringSpec) {
return JSON.parse(stringSpec, (k, v) => {
if (typeof v === 'string' && v.startsWith('__FUNCTION__')) {
const funcBody = v.slice(12); // 移除标记
try {
return new Function('return (' + funcBody + ')')();
} catch(e) {
console.error('函数解析失败:', e);
return () => {};
}
}
return v;
});
}
const spec = parseSpec(\`${serializeSpec(spec)}\`);
const chart = new VChart.VChart(spec, {
dom: 'chart-container'
});
chart.renderSync();
</script>
</body>
</html>
`;
}
/**
* get file path saved string
* @param isUpdate {boolean} default: false, update existed file when is true
*/
function getSavedPathName(
directory: string,
fileName: string,
outputType: "html" | "png" | "json" | "md",
isUpdate: boolean = false
) {
let newFileName = fileName;
while (
!isUpdate &&
fs.existsSync(
path.join(directory, "visualization", `${newFileName}.${outputType}`)
)
) {
newFileName += "_new";
}
return path.join(directory, "visualization", `${newFileName}.${outputType}`);
}
const readStdin = (): Promise<string> => {
return new Promise((resolve) => {
let input = "";
process.stdin.setEncoding("utf-8"); // 确保编码与 Python 端一致
process.stdin.on("data", (chunk) => (input += chunk));
process.stdin.on("end", () => resolve(input));
});
};
/** Save insights markdown in local, and return content && path */
const setInsightTemplate = (
path: string,
title: string,
insights: string[]
) => {
let res = "";
if (insights.length) {
res += `## ${title} Insights`;
insights.forEach((insight, index) => {
res += `\n${index + 1}. ${insight}`;
});
}
if (res) {
fs.writeFileSync(path, res, "utf-8");
return { insight_path: path, insight_md: res };
}
return {};
};
/** Save vmind result into local file, Return chart file path */
async function saveChartRes(options: {
spec: any;
directory: string;
outputType: "png" | "html";
fileName: string;
width?: number;
height?: number;
isUpdate?: boolean;
}) {
const { directory, fileName, spec, outputType, width, height, isUpdate } =
options;
const specPath = getSavedPathName(directory, fileName, "json", isUpdate);
fs.writeFileSync(specPath, JSON.stringify(spec, null, 2));
const savedPath = getSavedPathName(directory, fileName, outputType, isUpdate);
if (outputType === "png") {
const base64 = await getBase64(spec, width, height);
fs.writeFileSync(savedPath, base64);
} else {
const html = getHtmlVChart(spec, width, height);
fs.writeFileSync(savedPath, html, "utf-8");
}
return savedPath;
}
async function generateChart(
vmind: VMind,
options: {
dataset: string | DataTable;
userPrompt: string;
directory: string;
outputType: "png" | "html";
fileName: string;
width?: number;
height?: number;
language?: "en" | "zh";
}
) {
let res: {
chart_path?: string;
error?: string;
insight_path?: string;
insight_md?: string;
} = {};
const {
dataset,
userPrompt,
directory,
width,
height,
outputType,
fileName,
language,
} = options;
try {
// Get chart spec and save in local file
const jsonDataset = isString(dataset) ? JSON.parse(dataset) : dataset;
const { spec, error, chartType } = await vmind.generateChart(
userPrompt,
undefined,
jsonDataset,
{
enableDataQuery: false,
theme: "light",
}
);
if (error || !spec) {
return {
error: error || "Spec of Chart was Empty!",
};
}
spec.title = {
text: userPrompt,
};
if (!fs.existsSync(path.join(directory, "visualization"))) {
fs.mkdirSync(path.join(directory, "visualization"));
}
const specPath = getSavedPathName(directory, fileName, "json");
res.chart_path = await saveChartRes({
directory,
spec,
width,
height,
fileName,
outputType,
});
// get chart insights and save in local
const insights = [];
if (
chartType &&
[
ChartType.BarChart,
ChartType.LineChart,
ChartType.AreaChart,
ChartType.ScatterPlot,
ChartType.DualAxisChart,
].includes(chartType)
) {
const { insights: vmindInsights } = await vmind.getInsights(spec, {
maxNum: 6,
algorithms: [
AlgorithmType.OverallTrending,
AlgorithmType.AbnormalTrend,
AlgorithmType.PearsonCorrelation,
AlgorithmType.SpearmanCorrelation,
AlgorithmType.StatisticsAbnormal,
AlgorithmType.LOFOutlier,
AlgorithmType.DbscanOutlier,
AlgorithmType.MajorityValue,
AlgorithmType.PageHinkley,
AlgorithmType.TurningPoint,
AlgorithmType.StatisticsBase,
AlgorithmType.Volatility,
],
usePolish: false,
language: language === "en" ? "english" : "chinese",
});
insights.push(...vmindInsights);
}
const insightsText = insights
.map((insight) => insight.textContent?.plainText)
.filter((insight) => !!insight) as string[];
spec.insights = insights;
fs.writeFileSync(specPath, JSON.stringify(spec, null, 2));
res = {
...res,
...setInsightTemplate(
getSavedPathName(directory, fileName, "md"),
userPrompt,
insightsText
),
};
} catch (error: any) {
res.error = error.toString();
} finally {
return res;
}
}
async function updateChartWithInsight(
vmind: VMind,
options: {
directory: string;
outputType: "png" | "html";
fileName: string;
insightsId: number[];
}
) {
const { directory, outputType, fileName, insightsId } = options;
let res: { error?: string; chart_path?: string } = {};
try {
const specPath = getSavedPathName(directory, fileName, "json", true);
const spec = JSON.parse(fs.readFileSync(specPath, "utf8"));
// llm select index from 1
const insights = (spec.insights || []).filter(
(_insight: any, index: number) => insightsId.includes(index + 1)
);
const { newSpec, error } = await vmind.updateSpecByInsights(spec, insights);
if (error) {
throw error;
}
res.chart_path = await saveChartRes({
spec: newSpec,
directory,
outputType,
fileName,
isUpdate: true,
});
} catch (error: any) {
res.error = error.toString();
} finally {
return res;
}
}
async function executeVMind() {
const input = await readStdin();
const inputData = JSON.parse(input);
let res;
const {
llm_config,
width,
dataset = [],
height,
directory,
user_prompt: userPrompt,
output_type: outputType = "png",
file_name: fileName,
task_type: taskType = "visualization",
insights_id: insightsId = [],
language = "en",
} = inputData;
const { base_url: baseUrl, model, api_key: apiKey } = llm_config;
const vmind = new VMind({
url: `${baseUrl}/chat/completions`,
model,
headers: {
"api-key": apiKey,
Authorization: `Bearer ${apiKey}`,
},
});
if (taskType === "visualization") {
res = await generateChart(vmind, {
dataset,
userPrompt,
directory,
outputType,
fileName,
width,
height,
language,
});
} else if (taskType === "insight" && insightsId.length) {
res = await updateChartWithInsight(vmind, {
directory,
fileName,
outputType,
insightsId,
});
}
console.log(JSON.stringify(res));
}
executeVMind();
|