File size: 10,634 Bytes
216c0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import sys
import random
import argparse
from logging import getLogger

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from modules.chart_engine.template.template_registry import get_template_for_chart_type, get_template_for_chart_name
from modules.chart_engine.utils.load_charts import render_chart_to_svg
from modules.chart_engine.utils.file_utils import create_temp_file, cleanup_temp_file, ensure_temp_dir, create_fallback_svg
import importlib

logger = getLogger(__name__)

def load_data_from_json(json_file_path="input.json"):
    """
    Load chart data from a JSON file
    
    Args:
        json_file_path: Path to the JSON file
        
    Returns:
        Dict containing the JSON data
    """
    with open(json_file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def process(input: str, output: str, chart_name: str = None, html_output: str = None) -> bool:
    """
    Pipeline入口函数,处理单个文件的图表生成
    
    Args:
        input: 输入JSON文件路径
        output: 输出SVG文件路径
        chart_name: 图表名称(可选)
        html_output: HTML输出路径(可选)
        
    Returns:
        bool: 处理是否成功
    """
    try:
        # Ensure tmp directory exists
        tmp_dir = ensure_temp_dir()
        
        # Load data from input JSON file
        try:
            json_data = load_data_from_json(input)
            logger.info(f"Loaded data from {input}")
        except Exception as e:
            logger.error(f"Error loading JSON data from {input}: {e}")
            return False
        
        # Determine chart name (from args, JSON, or default)
        if chart_name is None:
            # Try to get chart name from JSON data
            chart_name = json_data.get("chart_name", "donut_chart_01")
        
        logger.info(f"Using chart name: {chart_name}")
        
        # Get the appropriate template for this chart type
        engine_preference = None
        engine, template = get_template_for_chart_name(chart_name, engine_preference=engine_preference)
        
        if engine is None:
            logger.error(f"No template found for chart name '{chart_name}'")
            return False
        
        logger.info(f"Using {engine} template for {chart_name}")
        
        # Get dimensions from JSON data
        width = json_data.get("variables", {}).get("width", 1200)
        height = json_data.get("variables", {}).get("height", 800)
        logger.info(f"Using dimensions: {width}x{height}")
        
        # Determine output SVG path
        if output:
            output_svg_path = output
        else:
            # Generate a random output SVG filename in tmp directory
            output_svg_path = os.path.join(tmp_dir, input.split('.')[0].split('/')[-1] + "_" + f"{chart_name.replace(' ', '_')}.svg")
        
        svg_file = None
        error_message = None
        
        try:
            if engine == 'echarts_py':
                # Use Python template
                options = template.make_options(json_data)
                
                # Save options to temporary file
                echarts_options_file = create_temp_file(prefix="echarts_options_", suffix=".json", 
                                                    content=json.dumps(options, indent=2))
                
                # Use same renderer as echarts-js
                logger.info(f"Using ECharts renderer for Python-generated options")
                
                # Create JS wrapper function
                js_wrapper_content = f"""
                function make_option(jsonData) {{
                    return {json.dumps(options)};
                }}
                """
                
                js_wrapper_file = create_temp_file(prefix="echarts_wrapper_", suffix=".js", 
                                                content=js_wrapper_content)
                
                try:
                    # Render SVG
                    svg_file = render_chart_to_svg(
                        json_data=json_data,
                        output_svg_path=output_svg_path,
                        js_file=js_wrapper_file,
                        width=width,
                        height=height,
                        framework="echarts"
                    )
                    
                    if svg_file is None:
                        raise ValueError("SVG chart generation failed (returned None)")
                    
                    logger.info(f"ECharts SVG chart generated successfully")
                    
                finally:
                    # Clean up temporary files
                    cleanup_temp_file(js_wrapper_file)
                    cleanup_temp_file(echarts_options_file)
                
            elif engine == 'echarts-js':
                # Use unified render_chart_to_svg function
                try:
                    svg_file = render_chart_to_svg(
                        json_data=json_data,
                        output_svg_path=output_svg_path,
                        js_file=template,
                        width=width,
                        height=height,
                        framework="echarts",
                        html_output_path=html_output,
                    )
                    
                    if svg_file is None:
                        raise ValueError("SVG chart generation failed (returned None)")
                    
                    logger.info(f"ECharts SVG chart generated successfully")
                    
                except Exception as e:
                    error_message = str(e)
                    raise Exception(f"Failed to generate ECharts JavaScript chart: {error_message}")
            
            elif engine == 'd3-js':
                # Use unified render_chart_to_svg function
                try:
                    svg_file = render_chart_to_svg(
                        json_data=json_data,
                        output_svg_path=output_svg_path,
                        js_file=template,
                        width=width,
                        height=height,
                        framework="d3",
                        html_output_path=html_output,
                    )
                    
                    if svg_file is None:
                        raise ValueError("SVG chart generation failed (returned None)")
                    
                    logger.info(f"D3.js SVG chart generated successfully")
                    
                except Exception as e:
                    error_message = str(e)
                    raise Exception(f"Failed to generate D3.js chart: {error_message}")
                    
            elif engine == 'vegalite_py':
                # Use vegalite_py template
                template_root = "template.vegalite_py"
                general_chart_type = template.split('/')[-2]
                module_name = template.split('/')[-1].split('.')[0]
                module_path = f"{template_root}.{general_chart_type}.{module_name}"
                module = importlib.import_module(module_path)
                
                chart_words = module_name.split('_')
                chart_words = [word.capitalize() for word in chart_words]
                chart_type = ''.join(chart_words)
                
                template_class = getattr(module, chart_type)
                template_object = template_class(json_data)
                vega_spec = template_object.make_specification(json_data)
                
                vega_spec_file = create_temp_file(prefix="vega_spec_", suffix=".json", 
                                                content=json.dumps(vega_spec, indent=2))
                
                try:
                    svg_file, svg_content = template_object.specification_to_svg(vega_spec, output_svg_path)
                    if svg_file is None:
                        raise ValueError("SVG chart generation failed (returned None)")
                    
                    element_tree = template_object.svg_to_element_tree(svg_content)
                    template_object.apply_variation(json_data)
                    svg_file = output_svg_path
                    svg_content = template_object.element_tree_to_svg(template_object.elements_tree)
                    with open(output_svg_path, 'w', encoding='utf-8') as f:
                        f.write(svg_content)
                    logger.info(f"VegaLite SVG chart generated successfully")
                    
                finally:
                    cleanup_temp_file(vega_spec_file)
            else:
                error_message = f"Unknown engine type: {engine}"
                logger.error(error_message)
                return False
            
            if svg_file is not None and os.path.exists(svg_file):
                logger.info(f"Final SVG output: {svg_file}")
                return True
            else:
                logger.error("Error: No SVG file was generated")
                return False
                
        except Exception as e:
            logger.error(f"Error generating chart: {e}")
            return False
            
    except Exception as e:
        logger.error(f"Error in chart generation process: {e}")
        return False

def parse_arguments():
    """
    Parse command-line arguments
    
    Returns:
        Namespace containing the parsed arguments
    """
    parser = argparse.ArgumentParser(description='Generate chart SVG from JSON data')
    parser.add_argument('--input', type=str, default='input.json',
                        help='Path to input JSON file (default: input.json)')
    parser.add_argument('--output', type=str, default=None,
                        help='Path to output SVG file (default: auto-generated in tmp directory)')
    parser.add_argument('--name', type=str, default=None,
                        help='Chart name to use (default: uses value from JSON or a default name)')
    parser.add_argument('--html', type=str, default=None,
                        help='Path to save intermediate HTML file (default: not saved)')
    
    return parser.parse_args()

if __name__ == '__main__':
    # Parse command-line arguments
    args = parse_arguments()
    
    success = process(
        input=args.input,
        output=args.output,
        chart_name=args.name,
        html_output=args.html
    )
    
    if success:
        print("Chart generation succeeded.")
    else:
        print("Chart generation failed.")
        sys.exit(1)