|
| 1 | +""" |
| 2 | +行业研究报告生成脚本 |
| 3 | +
|
| 4 | +功能: |
| 5 | +- 根据用户输入的行业关键词,生成行业深度研究报告。 |
| 6 | +- 结果输出的行业研究报告内容:最终返回标题、正文、PDF/DOC附件、溯源信息。 |
| 7 | +
|
| 8 | +需要配置EM_API_KEY。 |
| 9 | +""" |
| 10 | + |
| 11 | +import asyncio |
| 12 | +import json |
| 13 | +import os |
| 14 | +from pathlib import Path |
| 15 | +import httpx |
| 16 | +import base64 |
| 17 | +import argparse |
| 18 | +import sys |
| 19 | + |
| 20 | +# █████████████████████████████████████████████████████████████████████████ |
| 21 | +# ██ ██ |
| 22 | +# ██ ███████╗███╗ ███╗ █████╗ ██████╗ ██╗ ██╗ ██████╗ ██ |
| 23 | +# ██ ██╔════╝████╗ ████║ ██╔══██╗██╔══██╗██║ ██║██╔═══██╗ ██ |
| 24 | +# ██ █████╗ ██╔████╔██║ ███████║██████╔╝██║ █╗ ██║██║ ██║ ██ |
| 25 | +# ██ ██╔══╝ ██║╚██╔╝██║ ██╔══██║██╔═══╝ ██║███╗██║██║ ██║ ██ |
| 26 | +# ██ ███████╗██║ ╚═╝ ██║ ██║ ██║██║ ╚███╔███╔╝╚██████╔╝ ██ |
| 27 | +# ██ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚══╝╚══╝ ╚═════╝ ██ |
| 28 | +# ██ ██ |
| 29 | +# ██ ⚠️ EM API KEY CONFIGURATION REQUIRED ⚠️ ██ |
| 30 | +# ██ ██ |
| 31 | +# ██ YOU MUST SET THE ENVIRONMENT VARIABLE BEFORE RUNNING ██ |
| 32 | +# ██ ██ |
| 33 | +# ██ ENV VARIABLE: EM_API_KEY ██ |
| 34 | +# ██ ██ |
| 35 | +# ██ Example (Linux / macOS): ██ |
| 36 | +# ██ export EM_API_KEY="your_em_api_key" ██ |
| 37 | +# ██ ██ |
| 38 | +# ██ Example (Windows PowerShell): ██ |
| 39 | +# ██ $env:EM_API_KEY="your_em_api_key" ██ |
| 40 | +# ██ ██ |
| 41 | +# █████████████████████████████████████████████████████████████████████████ |
| 42 | + |
| 43 | + |
| 44 | +EM_API_KEY = os.environ.get("EM_API_KEY", "") |
| 45 | + |
| 46 | +if not EM_API_KEY: |
| 47 | + raise RuntimeError( |
| 48 | + """ |
| 49 | +
|
| 50 | +╔══════════════════════════════════════════════════════════════╗ |
| 51 | +║ EM API KEY REQUIRED ║ |
| 52 | +╠══════════════════════════════════════════════════════════════╣ |
| 53 | +║ Environment variable EM_API_KEY is not set. ║ |
| 54 | +║ ║ |
| 55 | +║ Please configure the environment variable first: ║ |
| 56 | +║ ║ |
| 57 | +║ Linux / macOS: ║ |
| 58 | +║ export EM_API_KEY="your_em_api_key" ║ |
| 59 | +║ ║ |
| 60 | +║ Windows PowerShell: ║ |
| 61 | +║ $env:EM_API_KEY="your_em_api_key" ║ |
| 62 | +║ ║ |
| 63 | +║ Then run the program again. ║ |
| 64 | +╚══════════════════════════════════════════════════════════════╝ |
| 65 | +
|
| 66 | +""" |
| 67 | + ) |
| 68 | + |
| 69 | + |
| 70 | +SKILL_NAME = "industry_research_report" |
| 71 | +DEFAULT_OUTPUT_DIR = Path.cwd() / "miaoxiang" / SKILL_NAME |
| 72 | +print('默认输出目录为:',DEFAULT_OUTPUT_DIR.absolute()) |
| 73 | +# MCP 服务器地址 |
| 74 | +MCP_URL = "https://ai-saas.eastmoney.com/proxy/app-robo-advisor-api/assistant/write/industry/research" |
| 75 | + |
| 76 | + |
| 77 | +def _save_base64_file(b64_str: str, file_path: Path) -> bool: |
| 78 | + """将 base64 字符串解码后写入文件。""" |
| 79 | + if not b64_str: |
| 80 | + return False |
| 81 | + try: |
| 82 | + raw = base64.b64decode(b64_str) |
| 83 | + file_path.parent.mkdir(parents=True, exist_ok=True) |
| 84 | + file_path.write_bytes(raw) |
| 85 | + return True |
| 86 | + except Exception as exc: |
| 87 | + print(f"[WARN] 保存附件失败 ({file_path.name}): {exc}", file=sys.stderr) |
| 88 | + return False |
| 89 | + |
| 90 | + |
| 91 | +def run_cli() -> None: |
| 92 | + """命令行入口:从参数或 stdin 读取查询文本,执行并打印结果路径。""" |
| 93 | + |
| 94 | + parser = argparse.ArgumentParser(description='通过行业名称获取该行业的深度研究报告') |
| 95 | + |
| 96 | + # 添加query参数 |
| 97 | + parser.add_argument('--query', type=str, help='自然语言查询,如「股价大于1000元的股票」', required=True) |
| 98 | + |
| 99 | + args = parser.parse_args() |
| 100 | + |
| 101 | + print(f"行业名称: {args.query}") |
| 102 | + |
| 103 | + if not args.query.strip(): |
| 104 | + print("用法: python3 scripts/get_data.py --query \"行业名称\"") |
| 105 | + print("示例: 半导体 / 新能源汽车 / AI芯片 / 消费电子与智能家居") |
| 106 | + sys.exit(1) |
| 107 | + |
| 108 | + async def _main() -> None: |
| 109 | + output_dir = Path(os.environ.get(SKILL_NAME + "_OUTPUT_DIR", str(DEFAULT_OUTPUT_DIR))) |
| 110 | + r = await get_industry_research_report(args.query, output_dir=output_dir) |
| 111 | + if "error" in r: |
| 112 | + print(f"错误: {r['error']}", file=sys.stderr) |
| 113 | + sys.exit(2) |
| 114 | + |
| 115 | + print(json.dumps(r, ensure_ascii=False, indent=4)) |
| 116 | + |
| 117 | + loop = asyncio.new_event_loop() |
| 118 | + asyncio.set_event_loop(loop) |
| 119 | + try: |
| 120 | + loop.run_until_complete(_main()) |
| 121 | + finally: |
| 122 | + loop.close() |
| 123 | + |
| 124 | + |
| 125 | +async def get_industry_research_report(query: str, output_dir: Path): |
| 126 | + """行业研究报告 异步调用函数""" |
| 127 | + |
| 128 | + result_data = {} |
| 129 | + |
| 130 | + if not isinstance(query, str) or len(query) > 500: |
| 131 | + result_data["error"] = "字数超出限制,请尝试其它主体。" |
| 132 | + return result_data |
| 133 | + |
| 134 | + try: |
| 135 | + async with httpx.AsyncClient(timeout=1200.0) as client: |
| 136 | + result = await client.post( |
| 137 | + MCP_URL, |
| 138 | + json={"query": query}, |
| 139 | + headers={ |
| 140 | + "Content-Type": "application/json", |
| 141 | + "em_api_key": EM_API_KEY, |
| 142 | + }, |
| 143 | + ) |
| 144 | + |
| 145 | + result.raise_for_status() |
| 146 | + |
| 147 | + result_data_api = result.json() |
| 148 | + |
| 149 | + title = result_data_api["data"]["title"] |
| 150 | + content = result_data_api["data"]["content"] |
| 151 | + share_url = result_data_api["data"]["shareUrl"] |
| 152 | + |
| 153 | + pdf_output_path = output_dir / f"{title}.pdf" |
| 154 | + pdf_saved = _save_base64_file(result_data_api["data"]["pdfBase64"], pdf_output_path) |
| 155 | + |
| 156 | + word_output_path = output_dir / f"{title}.docx" |
| 157 | + word_saved = _save_base64_file(result_data_api["data"]["wordBase64"], word_output_path) |
| 158 | + |
| 159 | + if not word_saved or not pdf_saved: |
| 160 | + result_data["error"] = "保存附件失败" |
| 161 | + return result_data |
| 162 | + |
| 163 | + result_data["title"] = title |
| 164 | + result_data["truncated_text"] = content |
| 165 | + result_data["pdf_output_path"] = str(pdf_output_path) |
| 166 | + result_data["docx_output_path"] = str(word_output_path) |
| 167 | + result_data["share_url"] = share_url |
| 168 | + |
| 169 | + return result_data |
| 170 | + |
| 171 | + |
| 172 | + except Exception as e: |
| 173 | + print(f"调用工具时出错: {e}", file=sys.stderr) |
| 174 | + result_data["error"] = f"调用工具时出错: {e}" |
| 175 | + import traceback |
| 176 | + traceback.print_exc() |
| 177 | + return result_data |
| 178 | + |
| 179 | + |
| 180 | +if __name__ == "__main__": |
| 181 | + run_cli() |
0 commit comments