feat(工具): 添加代码分析工具模块

- 新增 codeAnalyzer.ts 用于分析代码特征
- 实现 detectGraphicsCode 检测图形绘制代码
- 实现 shouldUsePyodide 判断是否使用浏览器端执行
- 支持 matplotlib、seaborn、plotly 等可视化库检测
This commit is contained in:
gaoziman 2025-12-19 20:18:11 +08:00
parent bfcaf5a53a
commit ba4e00a341

View File

@ -0,0 +1,107 @@
/**
*
*
*
*/
// 加载状态回调类型(定义在这里以便服务端使用)
export type LoadingCallback = (status: {
stage: 'loading' | 'ready' | 'error';
message: string;
progress?: number;
}) => void;
/**
*
*/
export function detectGraphicsCode(code: string): boolean {
const graphicsKeywords = [
// matplotlib
'matplotlib',
'pyplot',
'plt.',
'.plot(',
'.scatter(',
'.bar(',
'.barh(',
'.hist(',
'.pie(',
'.boxplot(',
'.violinplot(',
'.heatmap(',
'.imshow(',
'.contour(',
'.fill(',
'.errorbar(',
'.stem(',
'.step(',
'savefig',
'show()',
'.figure(',
'.subplot(',
'.subplots(',
// seaborn
'seaborn',
'sns.',
// plotly
'plotly',
'px.',
'go.Figure',
// 其他可视化库
'bokeh',
'altair',
];
const lowerCode = code.toLowerCase();
return graphicsKeywords.some(keyword => lowerCode.includes(keyword.toLowerCase()));
}
/**
* 使 Pyodide
* @param code
* @param language
* @returns Pyodide
*/
export function shouldUsePyodide(code: string, language: string): boolean {
// 只有 Python 代码才考虑使用 Pyodide
if (!['python', 'python3', 'py'].includes(language.toLowerCase())) {
return false;
}
// 如果代码包含图形绘制,需要使用 Pyodide
return detectGraphicsCode(code);
}
/**
*
*/
export interface CodeAnalysis {
language: string;
hasGraphics: boolean;
requiresPyodide: boolean;
estimatedComplexity: 'simple' | 'medium' | 'complex';
}
/**
*
*/
export function analyzeCode(code: string, language: string): CodeAnalysis {
const hasGraphics = detectGraphicsCode(code);
const requiresPyodide = shouldUsePyodide(code, language);
// 估算复杂度
const lines = code.split('\n').filter(l => l.trim()).length;
let complexity: 'simple' | 'medium' | 'complex' = 'simple';
if (lines > 50 || hasGraphics) {
complexity = 'complex';
} else if (lines > 20) {
complexity = 'medium';
}
return {
language: language.toLowerCase(),
hasGraphics,
requiresPyodide,
estimatedComplexity: complexity,
};
}