import json import subprocess import tempfile import os from json_openai import llm_format_text, EXTRACT_OUNTLINE_SYSTEM_PROMPT def create_temp_test_file(markdown_content): """创建临时的TypeScript测试文件""" test_content = f'''import {{ markdownToJSON }} from './markdownToJSON.js'; // AI生成的Markdown内容 const markdown = `{markdown_content}`; // 转换并输出结果 const result = markdownToJSON(markdown); console.log('转换结果:'); console.log(JSON.stringify(result, null, 2)); ''' with open('temp_test_markdown.ts', 'w', encoding='utf-8') as f: f.write(test_content) return 'temp_test_markdown.ts' def run_typescript_converter(test_file): """编译并运行TypeScript测试文件""" try: # 编译TypeScript文件 compile_result = subprocess.run([ 'npx', 'tsc', test_file, '--outDir', 'dist', '--target', 'ES2020', '--module', 'ES2020' ], capture_output=True, text=True) if compile_result.returncode != 0: print(f"编译错误: {compile_result.stderr}") return None # 运行编译后的JavaScript文件 js_file = test_file.replace('.ts', '.js').replace('./', 'dist/') run_result = subprocess.run([ 'node', js_file ], capture_output=True, text=True) if run_result.returncode == 0: return run_result.stdout else: print(f"运行错误: {run_result.stderr}") return None except Exception as e: print(f"执行TypeScript转换时出错: {e}") return None def main(): # 测试配置 model = "glm-4.5" base_url = "https://open.bigmodel.cn/api/paas/v4/" api_key = "ce39bdd4fcf34ec0aec75072bc9ff988.hAp7HZTVUwy7vImn" # 测试内容 test_content = """ 人工智能的发展历程 早期发展 人工智能的概念最早可以追溯到1950年代。图灵测试的提出标志着AI研究的开始。 图灵测试 图灵测试是判断机器是否具有智能的重要标准。 现代发展 近年来,深度学习技术的突破推动了AI的快速发展。 深度学习 深度学习通过神经网络模拟人脑的工作方式。 """ # 构建消息 messages = [ {"role": "system", "content": EXTRACT_OUNTLINE_SYSTEM_PROMPT}, {"role": "user", "content": f"请分析以下文章内容并转换为Markdown格式:\n\n{test_content}"} ] print("=== 第一步:AI处理生成Markdown ===") try: markdown_result = llm_format_text(model, base_url, api_key, messages, 2000) print("AI生成的Markdown:") print(markdown_result) print("\n" + "="*50 + "\n") print("=== 第二步:Markdown转换为JSON ===") # 创建临时测试文件 test_file = create_temp_test_file(markdown_result) # 运行TypeScript转换 json_result = run_typescript_converter(test_file) if json_result: print("转换后的JSON结构:") print(json_result) else: print("转换失败") # 清理临时文件 try: os.remove(test_file) js_file = test_file.replace('.ts', '.js').replace('./', 'dist/') if os.path.exists(js_file): os.remove(js_file) except: pass except Exception as e: print(f"处理失败: {e}") print("可能的原因:") print("1. API密钥无效或过期") print("2. 网络连接问题") print("3. API服务不可用") print("4. 模型名称不正确") if __name__ == "__main__": main()