-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
276 lines (239 loc) · 10 KB
/
Copy pathreport.py
File metadata and controls
276 lines (239 loc) · 10 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
import io
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.lib.colors import HexColor
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from datetime import datetime
# 한글 폰트 등록
pdfmetrics.registerFont(TTFont('NanumGothic', 'fonts/NanumGothic-Regular.ttf'))
pdfmetrics.registerFont(TTFont('NanumGothicBold', 'fonts/NanumGothic-Bold.ttf'))
def get_styles():
"""PDF용 스타일 정의"""
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(
name='KoreanTitle',
fontName='NanumGothicBold',
fontSize=22,
alignment=TA_CENTER,
spaceAfter=10
))
styles.add(ParagraphStyle(
name='KoreanHeading',
fontName='NanumGothicBold',
fontSize=14,
spaceBefore=15,
spaceAfter=8,
textColor=HexColor('#333333')
))
styles.add(ParagraphStyle(
name='KoreanBody',
fontName='NanumGothic',
fontSize=10,
leading=16,
spaceAfter=6
))
styles.add(ParagraphStyle(
name='KoreanSmall',
fontName='NanumGothic',
fontSize=9,
leading=14,
textColor=HexColor('#555555')
))
return styles
def create_wpm_chart(wpm_data):
"""WPM 그래프를 이미지로 생성"""
matplotlib.rcParams['font.family'] = 'Malgun Gothic'
matplotlib.rcParams['axes.unicode_minus'] = False
times = [seg["start"] for seg in wpm_data["segments"]]
wpms = [seg["wpm"] for seg in wpm_data["segments"]]
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(times, wpms, marker='o', color='#4ECDC4', linewidth=2, markersize=4)
ax.axhline(y=80, color='orange', linestyle='--', label='느림 기준 (80)')
ax.axhline(y=120, color='red', linestyle='--', label='빠름 기준 (120)')
ax.fill_between(times, 80, 120, alpha=0.1, color='green')
ax.set_xlabel("시간 (초)")
ax.set_ylabel("WPM")
ax.set_title("구간별 말하기 속도")
ax.legend(fontsize=8)
plt.tight_layout()
img_buffer = io.BytesIO()
fig.savefig(img_buffer, format='png', dpi=150)
plt.close(fig)
img_buffer.seek(0)
return img_buffer
def create_filler_chart(filler_data):
"""Filler word 막대 그래프를 이미지로 생성"""
matplotlib.rcParams['font.family'] = 'Malgun Gothic'
matplotlib.rcParams['axes.unicode_minus'] = False
if not filler_data["detected"]:
return None
words = [item["word"] for item in filler_data["detected"]]
counts = [item["count"] for item in filler_data["detected"]]
fig, ax = plt.subplots(figsize=(6, 3))
bars = ax.bar(words, counts, color='#FF6B6B')
ax.set_ylabel("횟수")
ax.set_title("Filler Word 빈도")
for bar, count in zip(bars, counts):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.1,
str(count), ha='center', fontsize=11)
plt.tight_layout()
img_buffer = io.BytesIO()
fig.savefig(img_buffer, format='png', dpi=150)
plt.close(fig)
img_buffer.seek(0)
return img_buffer
def generate_pdf(analysis, wpm_data, transcript):
"""분석 결과를 PDF로 생성하여 BytesIO로 반환"""
buffer = io.BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=A4,
topMargin=20*mm,
bottomMargin=20*mm,
leftMargin=20*mm,
rightMargin=20*mm
)
styles = get_styles()
story = []
# ===== 제목 =====
story.append(Paragraph("🎤 PresentAI 분석 리포트", styles['KoreanTitle']))
story.append(Paragraph(
f"생성일: {datetime.now().strftime('%Y년 %m월 %d일 %H:%M')}",
styles['KoreanSmall']
))
story.append(Spacer(1, 10*mm))
# ===== 1. 완성도 점수 =====
story.append(Paragraph("1. 완성도 점수", styles['KoreanHeading']))
score = analysis["completeness_score"]
score_data = [
["종합 점수", "논리 구조\n(/ 35점)", "Filler & 반복\n(/ 25점)", "말하기 속도\n(/ 20점)", "표현 정확성\n(/ 20점)"],
[
str(score["total"]) + "점",
str(score["breakdown"]["logic_structure"]) + "점",
str(score["breakdown"]["filler_and_repetition"]) + "점",
str(score["breakdown"]["speech_speed"]) + "점",
str(score["breakdown"]["expression_quality"]) + "점"
]
]
score_table = Table(score_data, colWidths=[90, 80, 80, 80, 80])
score_table.setStyle(TableStyle([
('FONTNAME', (0, 0), (-1, -1), 'NanumGothic'),
('FONTSIZE', (0, 0), (-1, 0), 9),
('FONTSIZE', (0, 1), (-1, 1), 12),
('FONTNAME', (0, 1), (0, 1), 'NanumGothicBold'),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('GRID', (0, 0), (-1, -1), 0.5, HexColor('#CCCCCC')),
('BACKGROUND', (0, 0), (-1, 0), HexColor('#F0F0F0')),
('BACKGROUND', (0, 1), (0, 1), HexColor('#E8F5E9')),
('ROWHEIGHT', (0, 0), (-1, -1), 35),
]))
story.append(score_table)
story.append(Spacer(1, 3*mm))
story.append(Paragraph(score["comment"], styles['KoreanBody']))
story.append(Spacer(1, 5*mm))
# ===== 2. Filler Words =====
story.append(Paragraph("2. Filler Words 분석", styles['KoreanHeading']))
filler = analysis["filler_words"]
story.append(Paragraph(f"총 감지 횟수: {filler['total_count']}회", styles['KoreanBody']))
filler_chart = create_filler_chart(filler)
if filler_chart:
story.append(Image(filler_chart, width=140*mm, height=70*mm))
story.append(Paragraph(filler["comment"], styles['KoreanSmall']))
story.append(Spacer(1, 5*mm))
# ===== 3. 반복 표현 =====
story.append(Paragraph("3. 반복 표현", styles['KoreanHeading']))
repeated = analysis["repeated_expressions"]
if repeated["detected"]:
for item in repeated["detected"]:
story.append(Paragraph(
f"• <b>{item['expression']}</b> — {item['count']}회 반복",
styles['KoreanBody']
))
story.append(Paragraph(repeated["comment"], styles['KoreanSmall']))
story.append(Spacer(1, 5*mm))
# ===== 4. 말하기 속도 =====
story.append(Paragraph("4. 말하기 속도 분석", styles['KoreanHeading']))
speed = analysis["speech_speed"]
story.append(Paragraph(
f"평균 WPM: {speed['average_wpm']} / 평가: {speed['evaluation']}",
styles['KoreanBody']
))
wpm_chart = create_wpm_chart(wpm_data)
story.append(Image(wpm_chart, width=160*mm, height=70*mm))
story.append(Paragraph(speed["comment"], styles['KoreanSmall']))
story.append(Spacer(1, 3*mm))
# 구간별 문장 + 속도 테이블
story.append(Paragraph("구간별 말하기 속도 상세", styles['KoreanBody']))
table_data = [["시간", "문장", "WPM", "평가"]]
for seg in wpm_data["segments"]:
wpm_val = seg["wpm"]
if wpm_val < 80:
evaluation = "느림"
elif wpm_val > 120:
evaluation = "빠름"
else:
evaluation = "적정"
table_data.append([
f"{seg['start']:.0f}s ~ {seg['end']:.0f}s",
Paragraph(seg["text"], styles['KoreanSmall']),
str(wpm_val),
evaluation
])
seg_table = Table(table_data, colWidths=[60, 230, 40, 40])
seg_table.setStyle(TableStyle([
('FONTNAME', (0, 0), (-1, -1), 'NanumGothic'),
('FONTSIZE', (0, 0), (-1, 0), 9),
('FONTSIZE', (0, 1), (-1, -1), 8),
('FONTNAME', (0, 0), (-1, 0), 'NanumGothicBold'),
('ALIGN', (0, 0), (-1, 0), 'CENTER'),
('ALIGN', (2, 1), (3, -1), 'CENTER'),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('GRID', (0, 0), (-1, -1), 0.5, HexColor('#CCCCCC')),
('BACKGROUND', (0, 0), (-1, 0), HexColor('#F0F0F0')),
('ROWHEIGHT', (0, 0), (-1, -1), 28),
]))
story.append(seg_table)
story.append(Spacer(1, 5*mm))
# ===== 5. 논리 구조 =====
story.append(Paragraph("5. 논리 구조 평가", styles['KoreanHeading']))
logic = analysis["logic_structure"]
intro = "✅ 있음" if logic["has_intro"] else "❌ 없음"
body = "✅ 있음" if logic["has_body"] else "❌ 없음"
conclusion = "✅ 있음" if logic["has_conclusion"] else "❌ 없음"
story.append(Paragraph(f"서론: {intro} / 본론: {body} / 결론: {conclusion}", styles['KoreanBody']))
story.append(Paragraph(logic["comment"], styles['KoreanSmall']))
story.append(Spacer(1, 5*mm))
# ===== 6. 표현 오류 =====
story.append(Paragraph("6. 표현 오류", styles['KoreanHeading']))
if "expression_errors" in analysis and analysis["expression_errors"]:
for err in analysis["expression_errors"]:
story.append(Paragraph(
f"❌ {err['original']} → ✅ {err['corrected']}",
styles['KoreanBody']
))
story.append(Paragraph(f" ({err['type']}) {err['reason']}", styles['KoreanSmall']))
else:
story.append(Paragraph("✅ 표현이 전부 적절하여 수정할 표현이 없습니다.", styles['KoreanBody']))
story.append(Spacer(1, 5*mm))
# ===== 7. 개선 문장 제안 =====
story.append(Paragraph("7. 개선 문장 제안", styles['KoreanHeading']))
for imp in analysis["improvements"]:
story.append(Paragraph(f"원문: {imp['original']}", styles['KoreanBody']))
story.append(Paragraph(f"개선: {imp['improved']}", styles['KoreanBody']))
story.append(Paragraph(f"💡 {imp['reason']}", styles['KoreanSmall']))
story.append(Spacer(1, 3*mm))
# ===== 8. 발표 원문 =====
story.append(Paragraph("8. 발표 원문 (STT 결과)", styles['KoreanHeading']))
story.append(Paragraph(transcript, styles['KoreanBody']))
# PDF 생성
doc.build(story)
buffer.seek(0)
return buffer