-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemo_generator.py
More file actions
369 lines (319 loc) · 12.3 KB
/
memo_generator.py
File metadata and controls
369 lines (319 loc) · 12.3 KB
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
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table,
TableStyle, PageBreak, Image
)
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT
from datetime import datetime
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
import io
import json
import re
def generate_policy_memo(topic, imf_content, wb_content, user_question, full_answer):
"""
生成专业的政策备忘录PDF
Args:
topic: 政策主题
imf_content: IMF相关内容片段列表
wb_content: World Bank相关内容片段列表
user_question: 用户的原始问题
full_answer: AI生成的完整回答
Returns:
BytesIO: PDF文件buffer
"""
# 1. 使用LLM生成结构化分析
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
analysis_prompt = ChatPromptTemplate.from_template("""
You are a Senior Policy Analyst preparing a briefing memo for an Executive Director at an international financial institution.
Based on the following analysis and source materials, create a structured policy brief:
Original Question: {question}
Full Analysis: {full_answer}
IMF Source Materials ({imf_count} excerpts):
{imf_content}
World Bank Source Materials ({wb_count} excerpts):
{wb_content}
Please provide a structured output in the following JSON format:
{{
"executive_summary": "2-3 sentence high-level summary",
"key_findings": [
"Finding 1",
"Finding 2",
"Finding 3"
],
"imf_perspective": "1 paragraph summarizing IMF's position",
"wb_perspective": "1 paragraph summarizing World Bank's position",
"comparative_analysis": "1 paragraph comparing and contrasting the two perspectives",
"policy_implications": [
"Implication 1",
"Implication 2"
],
"knowledge_gaps": "What information is missing or unclear?"
}}
Ensure the output is valid JSON only, with no additional text.
""")
# 格式化内容
imf_text = "\n\n".join([
f"Excerpt {i+1} (Page {doc.metadata.get('page', 'N/A')}):\n{doc.page_content[:400]}..."
for i, doc in enumerate(imf_content[:4])
]) if imf_content else "No IMF content available."
wb_text = "\n\n".join([
f"Excerpt {i+1} (Page {doc.metadata.get('page', 'N/A')}):\n{doc.page_content[:400]}..."
for i, doc in enumerate(wb_content[:4])
]) if wb_content else "No World Bank content available."
try:
response = llm.invoke(
analysis_prompt.format(
question=user_question,
full_answer=full_answer,
imf_content=imf_text,
wb_content=wb_text,
imf_count=len(imf_content),
wb_count=len(wb_content)
)
)
# 提取JSON(移除可能的markdown标记)
json_text = response.content
json_text = re.sub(r'```json\s*', '', json_text)
json_text = re.sub(r'```\s*', '', json_text)
json_text = json_text.strip()
analysis = json.loads(json_text)
except Exception as e:
# Fallback:如果JSON解析失败,使用默认结构
print(f"JSON parsing error: {e}")
analysis = {
"executive_summary": full_answer[:300] + "...",
"key_findings": ["See full analysis below"],
"imf_perspective": "See source materials",
"wb_perspective": "See source materials",
"comparative_analysis": full_answer[:500] + "...",
"policy_implications": ["Refer to detailed analysis"],
"knowledge_gaps": "Additional research may be needed"
}
# 2. 创建PDF
buffer = io.BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=letter,
topMargin=0.75*inch,
bottomMargin=0.75*inch,
leftMargin=1*inch,
rightMargin=1*inch
)
# 3. 定义样式
styles = getSampleStyleSheet()
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=18,
textColor=colors.HexColor('#1f4788'),
spaceAfter=6,
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
subtitle_style = ParagraphStyle(
'Subtitle',
parent=styles['Normal'],
fontSize=10,
textColor=colors.HexColor('#666666'),
alignment=TA_CENTER,
spaceAfter=20
)
heading_style = ParagraphStyle(
'CustomHeading',
parent=styles['Heading2'],
fontSize=13,
textColor=colors.HexColor('#2d5aa6'),
spaceAfter=8,
spaceBefore=16,
fontName='Helvetica-Bold',
borderPadding=(0, 0, 5, 0),
borderColor=colors.HexColor('#2d5aa6'),
borderWidth=0,
leftIndent=0
)
body_style = ParagraphStyle(
'CustomBody',
parent=styles['BodyText'],
fontSize=11,
alignment=TA_JUSTIFY,
spaceAfter=10,
leading=14
)
bullet_style = ParagraphStyle(
'Bullet',
parent=styles['Normal'],
fontSize=11,
leftIndent=20,
spaceAfter=8,
bulletIndent=10,
leading=14
)
# 4. 构建文档内容
story = []
# === 标题页 ===
story.append(Spacer(1, 0.5*inch))
story.append(Paragraph("POLICY ANALYSIS BRIEFING", title_style))
story.append(Paragraph(
f"{datetime.now().strftime('%B %d, %Y')}",
subtitle_style
))
# 主题框
topic_table = Table(
[[Paragraph(f"<b>TOPIC:</b> {topic[:150]}", styles['Normal'])]],
colWidths=[6*inch]
)
topic_table.setStyle(TableStyle([
('BOX', (0, 0), (-1, -1), 2, colors.HexColor('#1f4788')),
('BACKGROUND', (0, 0), (-1, -1), colors.HexColor('#f0f4f8')),
('TOPPADDING', (0, 0), (-1, -1), 12),
('BOTTOMPADDING', (0, 0), (-1, -1), 12),
('LEFTPADDING', (0, 0), (-1, -1), 15),
('RIGHTPADDING', (0, 0), (-1, -1), 15),
]))
story.append(topic_table)
story.append(Spacer(1, 0.3*inch))
# 元数据表格
metadata_data = [
['Prepared by:', 'PolicyGraph AI Analyst'],
['Analysis Date:', datetime.now().strftime('%B %d, %Y')],
['Sources:', f'IMF ({len(imf_content)} excerpts), World Bank ({len(wb_content)} excerpts)']
]
metadata_table = Table(metadata_data, colWidths=[1.5*inch, 4.5*inch])
metadata_table.setStyle(TableStyle([
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 9),
('TEXTCOLOR', (0, 0), (0, -1), colors.HexColor('#555555')),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('BOTTOMPADDING', (0, 0), (-1, -1), 6),
]))
story.append(metadata_table)
story.append(Spacer(1, 0.4*inch))
# 分隔线
story.append(Table([['']], colWidths=[6*inch],
style=[('LINEABOVE', (0,0), (-1,0), 2, colors.HexColor('#1f4788'))]))
story.append(Spacer(1, 0.3*inch))
# === EXECUTIVE SUMMARY ===
story.append(Paragraph("EXECUTIVE SUMMARY", heading_style))
story.append(Paragraph(analysis['executive_summary'], body_style))
story.append(Spacer(1, 0.2*inch))
# === KEY FINDINGS ===
story.append(Paragraph("KEY FINDINGS", heading_style))
for i, finding in enumerate(analysis['key_findings'], 1):
story.append(Paragraph(f"• {finding}", bullet_style))
story.append(Spacer(1, 0.2*inch))
# === ORGANIZATIONAL PERSPECTIVES ===
story.append(Paragraph("ORGANIZATIONAL PERSPECTIVES", heading_style))
# IMF Perspective
if imf_content:
story.append(Paragraph("<b>International Monetary Fund (IMF)</b>", body_style))
story.append(Paragraph(analysis['imf_perspective'], body_style))
story.append(Spacer(1, 0.15*inch))
# World Bank Perspective
if wb_content:
story.append(Paragraph("<b>World Bank Group</b>", body_style))
story.append(Paragraph(analysis['wb_perspective'], body_style))
story.append(Spacer(1, 0.2*inch))
# === COMPARATIVE ANALYSIS ===
story.append(Paragraph("COMPARATIVE ANALYSIS", heading_style))
story.append(Paragraph(analysis['comparative_analysis'], body_style))
story.append(Spacer(1, 0.2*inch))
# === 对比表格 ===
comparison_data = [
['Dimension', 'IMF Focus', 'World Bank Focus'],
[
'Primary Concern',
'Labor market risks\nMacroeconomic stability' if imf_content else 'N/A',
'Infrastructure development\nDigital inclusion' if wb_content else 'N/A'
],
[
'Geographic Focus',
'Advanced & emerging economies' if imf_content else 'N/A',
'Developing economies' if wb_content else 'N/A'
],
[
'Policy Tools',
'Fiscal & monetary frameworks' if imf_content else 'N/A',
'Investment & capacity building' if wb_content else 'N/A'
]
]
comparison_table = Table(comparison_data, colWidths=[1.5*inch, 2.25*inch, 2.25*inch])
comparison_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1f4788')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 10),
('FONTSIZE', (0, 1), (-1, -1), 9),
('BOTTOMPADDING', (0, 0), (-1, -1), 8),
('TOPPADDING', (0, 0), (-1, -1), 8),
('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')])
]))
story.append(comparison_table)
story.append(Spacer(1, 0.3*inch))
# === PAGE BREAK ===
story.append(PageBreak())
# === POLICY IMPLICATIONS ===
story.append(Paragraph("POLICY IMPLICATIONS & RECOMMENDATIONS", heading_style))
for i, implication in enumerate(analysis['policy_implications'], 1):
story.append(Paragraph(f"{i}. {implication}", bullet_style))
story.append(Spacer(1, 0.2*inch))
# === KNOWLEDGE GAPS ===
story.append(Paragraph("KNOWLEDGE GAPS & AREAS FOR FURTHER RESEARCH", heading_style))
story.append(Paragraph(analysis['knowledge_gaps'], body_style))
story.append(Spacer(1, 0.3*inch))
# === SOURCES ===
story.append(Paragraph("SOURCE DOCUMENTS", heading_style))
if imf_content:
story.append(Paragraph("<b>IMF Sources:</b>", body_style))
for i, doc in enumerate(imf_content[:5], 1):
source = doc.metadata.get('source', 'Unknown').split('\\')[-1]
page = doc.metadata.get('page', 'N/A')
story.append(Paragraph(
f"{i}. {source}, Page {page}",
bullet_style
))
story.append(Spacer(1, 0.1*inch))
if wb_content:
story.append(Paragraph("<b>World Bank Sources:</b>", body_style))
start_num = len(imf_content[:5]) + 1 if imf_content else 1
for i, doc in enumerate(wb_content[:5], start_num):
source = doc.metadata.get('source', 'Unknown').split('\\')[-1]
page = doc.metadata.get('page', 'N/A')
story.append(Paragraph(
f"{i}. {source}, Page {page}",
bullet_style
))
# === FOOTER ===
story.append(Spacer(1, 0.5*inch))
footer_style = ParagraphStyle(
'Footer',
parent=styles['Normal'],
fontSize=8,
textColor=colors.grey,
alignment=TA_CENTER
)
story.append(Table([['']], colWidths=[6*inch],
style=[('LINEABOVE', (0,0), (-1,0), 0.5, colors.grey)]))
story.append(Spacer(1, 0.1*inch))
story.append(Paragraph(
"This document was automatically generated by PolicyGraph AI Analyst | For internal use only",
footer_style
))
story.append(Paragraph(
f"Generated on {datetime.now().strftime('%B %d, %Y at %I:%M %p')}",
footer_style
))
# 5. 构建PDF
doc.build(story)
buffer.seek(0)
return buffer
# 测试函数
if __name__ == "__main__":
print("Memo generator module loaded successfully")