Spaces:
Sleeping
Sleeping
File size: 8,132 Bytes
54c99ad |
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 |
import pandas as pd
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from datetime import datetime
from typing import List, Dict
import os
def generate_csv(data, path="report.csv"):
"""Legacy function - kept for backwards compatibility"""
return generate_enhanced_csv(data, "Other", path)
def generate_enhanced_csv(
data: List[Dict],
interviewee_type: str,
path: str = "report.csv"
) -> str:
"""
Generate enhanced CSV with proper formatting and data validation
"""
if not data:
# Create empty CSV with headers
df = pd.DataFrame(columns=["Transcript ID", "Status"])
df.to_csv(path, index=False)
return path
# Create DataFrame
df = pd.DataFrame(data)
# Reorder columns for better readability
priority_cols = ["Transcript ID", "File Name", "Quality Score", "Word Count"]
other_cols = [col for col in df.columns if col not in priority_cols]
ordered_cols = [col for col in priority_cols if col in df.columns] + other_cols
df = df[ordered_cols]
# Save with proper encoding
df.to_csv(path, index=False, encoding='utf-8-sig')
return path
def generate_pdf(summary, details, path="report.pdf"):
"""Legacy function - kept for backwards compatibility"""
# Create minimal results structure
results = [{
"transcript_id": "Transcript 1",
"file_name": "analysis.txt",
"full_text": details,
"quality_score": 0.8,
"word_count": len(details.split())
}]
return generate_enhanced_pdf(summary, results, "Other", [], path)
def generate_enhanced_pdf(
summary: str,
results: List[Dict],
interviewee_type: str,
processing_errors: List[str],
path: str = "report.pdf"
) -> str:
"""
Generate professional PDF report with proper formatting
"""
# Create document
doc = SimpleDocTemplate(
path,
pagesize=letter,
rightMargin=0.75*inch,
leftMargin=0.75*inch,
topMargin=0.75*inch,
bottomMargin=0.75*inch
)
# Container for the 'Flowable' objects
story = []
# Define styles
styles = getSampleStyleSheet()
# Custom styles
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=24,
textColor=colors.HexColor('#1a1a1a'),
spaceAfter=30,
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
heading_style = ParagraphStyle(
'CustomHeading',
parent=styles['Heading2'],
fontSize=16,
textColor=colors.HexColor('#2c3e50'),
spaceAfter=12,
spaceBefore=20,
fontName='Helvetica-Bold'
)
subheading_style = ParagraphStyle(
'CustomSubheading',
parent=styles['Heading3'],
fontSize=13,
textColor=colors.HexColor('#34495e'),
spaceAfter=8,
spaceBefore=12,
fontName='Helvetica-Bold'
)
body_style = ParagraphStyle(
'CustomBody',
parent=styles['BodyText'],
fontSize=11,
leading=14,
textColor=colors.HexColor('#2c3e50'),
alignment=TA_LEFT
)
# Title page
story.append(Paragraph("Transcript Analysis Report", title_style))
story.append(Spacer(1, 0.2*inch))
# Metadata table
metadata = [
["Report Generated:", datetime.now().strftime("%B %d, %Y at %I:%M %p")],
["Interviewee Type:", interviewee_type],
["Total Transcripts:", str(len(results))],
["Successfully Processed:", str(sum(1 for r in results if r.get("quality_score", 0) > 0))]
]
metadata_table = Table(metadata, colWidths=[2*inch, 4*inch])
metadata_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (0, -1), colors.HexColor('#ecf0f1')),
('TEXTCOLOR', (0, 0), (-1, -1), colors.HexColor('#2c3e50')),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 10),
('BOTTOMPADDING', (0, 0), (-1, -1), 8),
('TOPPADDING', (0, 0), (-1, -1), 8),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#bdc3c7'))
]))
story.append(metadata_table)
story.append(Spacer(1, 0.3*inch))
# Executive Summary
story.append(Paragraph("Executive Summary", heading_style))
story.append(Spacer(1, 0.1*inch))
# Split summary into paragraphs
summary_paragraphs = summary.split('\n\n')
for para in summary_paragraphs:
if para.strip():
# Clean up text for PDF
clean_para = para.strip().replace('&', '&').replace('<', '<').replace('>', '>')
story.append(Paragraph(clean_para, body_style))
story.append(Spacer(1, 0.1*inch))
# Processing errors section (if any)
if processing_errors:
story.append(PageBreak())
story.append(Paragraph("Processing Issues", heading_style))
story.append(Spacer(1, 0.1*inch))
for error in processing_errors:
clean_error = error.replace('&', '&').replace('<', '<').replace('>', '>')
story.append(Paragraph(f"• {clean_error}", body_style))
story.append(Spacer(1, 0.05*inch))
# Individual transcript details
story.append(PageBreak())
story.append(Paragraph("Detailed Transcript Analysis", heading_style))
story.append(Spacer(1, 0.2*inch))
for result in results:
# Transcript header
transcript_title = f"{result['transcript_id']} - {result['file_name']}"
story.append(Paragraph(transcript_title, subheading_style))
# Stats
stats_data = [
["Quality Score:", f"{result['quality_score']:.2f}/1.00"],
["Word Count:", f"{result['word_count']:,}"]
]
stats_table = Table(stats_data, colWidths=[1.5*inch, 2*inch])
stats_table.setStyle(TableStyle([
('FONTSIZE', (0, 0), (-1, -1), 9),
('BOTTOMPADDING', (0, 0), (-1, -1), 4),
('TOPPADDING', (0, 0), (-1, -1), 4),
]))
story.append(stats_table)
story.append(Spacer(1, 0.1*inch))
# Analysis text
text = result['full_text']
# Split into manageable chunks and clean
chunks = text.split('\n\n')
for chunk in chunks[:10]: # Limit to prevent overly long PDFs
if chunk.strip():
clean_chunk = chunk.strip().replace('&', '&').replace('<', '<').replace('>', '>')
# Limit paragraph length
if len(clean_chunk) > 1000:
clean_chunk = clean_chunk[:1000] + "..."
story.append(Paragraph(clean_chunk, body_style))
story.append(Spacer(1, 0.1*inch))
story.append(Spacer(1, 0.2*inch))
# Page break between transcripts (except last)
if result != results[-1]:
story.append(PageBreak())
# Build PDF
try:
doc.build(story)
return path
except Exception as e:
print(f"[PDF Error] Failed to generate PDF: {e}")
# Create a minimal fallback PDF
simple_doc = SimpleDocTemplate(path, pagesize=letter)
simple_story = [
Paragraph("Transcript Analysis Report", title_style),
Paragraph(f"Error generating full report: {str(e)}", body_style),
Paragraph(summary, body_style)
]
simple_doc.build(simple_story)
return path |