Spaces:
Sleeping

Digitalytics / tests /report_generator.py
faseehsandhu's picture
added insights with extracted values,uses tool calling and test framework
db9343f
Raw History Blame Contribute Delete
21.1 kB
"""
report_generator.py
Generates comprehensive HTML and Markdown reports from accuracy analysis results.
"""
import json
import logging
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional
logger = logging.getLogger(__name__)
class ReportGenerator:
"""Generates human-readable accuracy reports."""
def __init__(self):
"""Initialize report generator."""
self.timestamp = datetime.now()
def generate_html_report(
self,
batch_analysis: Dict[str, Any],
output_file: Optional[str] = None
) -> str:
"""
Generate comprehensive HTML report.
Args:
batch_analysis: Output from AccuracyAnalyzer.analyze_batch()
output_file: Output file path (auto-generated if None)
Returns:
Path to generated HTML file
"""
if output_file is None:
output_dir = Path(__file__).parent / "test_reports"
output_dir.mkdir(exist_ok=True)
timestamp = self.timestamp.strftime("%Y%m%d_%H%M%S")
output_file = output_dir / f"accuracy_report_{timestamp}.html"
output_file = Path(output_file)
# Generate HTML
html_content = self._generate_html_content(batch_analysis)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_content)
logger.info(f"HTML report generated: {output_file}")
return str(output_file)
def generate_markdown_report(
self,
batch_analysis: Dict[str, Any],
output_file: Optional[str] = None
) -> str:
"""
Generate Markdown report.
Args:
batch_analysis: Output from AccuracyAnalyzer.analyze_batch()
output_file: Output file path (auto-generated if None)
Returns:
Path to generated Markdown file
"""
if output_file is None:
output_dir = Path(__file__).parent / "test_reports"
output_dir.mkdir(exist_ok=True)
timestamp = self.timestamp.strftime("%Y%m%d_%H%M%S")
output_file = output_dir / f"accuracy_report_{timestamp}.md"
output_file = Path(output_file)
# Generate Markdown
md_content = self._generate_markdown_content(batch_analysis)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(md_content)
logger.info(f"Markdown report generated: {output_file}")
return str(output_file)
def _generate_html_content(self, batch_analysis: Dict[str, Any]) -> str:
"""Generate HTML content for report."""
timestamp = self.timestamp.strftime("%Y-%m-%d %H:%M:%S")
total = batch_analysis.get("total_tests", 0)
passed = batch_analysis.get("passed_tests", 0)
failed = batch_analysis.get("failed_tests", 0)
avg_score = batch_analysis.get("average_score", 0)
pass_rate = batch_analysis.get("pass_rate", 0)
# Determine overall status color
status_color = "#22c55e" if pass_rate >= 0.8 else "#f59e0b" if pass_rate >= 0.6 else "#ef4444"
status_text = "βœ… EXCELLENT" if pass_rate >= 0.9 else "βœ… GOOD" if pass_rate >= 0.8 else "⚠️ FAIR" if pass_rate >= 0.6 else "❌ POOR"
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Dictionary Chatbot - Accuracy Report</title>
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
line-height: 1.6;
color: #333;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}}
.container {{
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 10px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
overflow: hidden;
}}
.header {{
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 40px;
text-align: center;
}}
.header h1 {{
font-size: 2.5em;
margin-bottom: 10px;
}}
.header p {{
font-size: 1em;
opacity: 0.9;
}}
.metrics {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
padding: 40px;
background: #f8f9fa;
border-bottom: 1px solid #e0e0e0;
}}
.metric {{
text-align: center;
padding: 20px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}}
.metric-value {{
font-size: 2em;
font-weight: bold;
color: #667eea;
margin: 10px 0;
}}
.metric-label {{
font-size: 0.9em;
color: #666;
text-transform: uppercase;
letter-spacing: 1px;
}}
.overall-status {{
font-size: 1.2em;
font-weight: bold;
padding: 20px;
border-radius: 8px;
background: {status_color};
color: white;
text-align: center;
}}
.content {{
padding: 40px;
}}
.section {{
margin-bottom: 40px;
}}
.section-title {{
font-size: 1.8em;
color: #333;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 3px solid #667eea;
}}
.test-result {{
margin-bottom: 20px;
padding: 20px;
border-left: 5px solid #ddd;
background: #f8f9fa;
border-radius: 4px;
}}
.test-result.passed {{
border-left-color: #22c55e;
background: #f0fdf4;
}}
.test-result.failed {{
border-left-color: #ef4444;
background: #fef2f2;
}}
.test-header {{
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}}
.test-name {{
font-weight: bold;
font-size: 1.1em;
color: #333;
}}
.test-id {{
color: #666;
font-size: 0.9em;
font-family: monospace;
}}
.test-score {{
font-size: 1.2em;
font-weight: bold;
padding: 5px 15px;
border-radius: 20px;
color: white;
}}
.test-score.excellent {{
background: #22c55e;
}}
.test-score.good {{
background: #3b82f6;
}}
.test-score.fair {{
background: #f59e0b;
}}
.test-score.poor {{
background: #ef4444;
}}
.validator-results {{
margin-top: 15px;
padding-top: 15px;
border-top: 1px solid #ddd;
}}
.validator {{
margin: 10px 0;
padding: 10px;
background: white;
border-radius: 4px;
border-left: 4px solid #667eea;
}}
.validator.passed {{
border-left-color: #22c55e;
}}
.validator.failed {{
border-left-color: #ef4444;
}}
.validator-name {{
font-weight: bold;
text-transform: uppercase;
font-size: 0.85em;
color: #667eea;
}}
.validator-score {{
font-size: 0.9em;
color: #666;
margin: 5px 0;
}}
.validator-issues {{
margin-top: 8px;
padding: 8px;
background: #fff5f5;
border-radius: 4px;
color: #c53030;
font-size: 0.85em;
}}
.issues-list {{
list-style: none;
margin: 5px 0 0 0;
padding-left: 0;
}}
.issues-list li {{
margin: 3px 0;
padding-left: 20px;
position: relative;
}}
.issues-list li:before {{
content: "β€’";
position: absolute;
left: 0;
color: #ef4444;
}}
.summary {{
background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);
padding: 30px;
border-radius: 8px;
margin-bottom: 40px;
}}
.summary-item {{
margin: 15px 0;
display: flex;
justify-content: space-between;
padding: 10px 0;
}}
.summary-label {{
font-weight: 600;
color: #333;
}}
.summary-value {{
color: #667eea;
font-weight: bold;
font-size: 1.1em;
}}
.footer {{
background: #f8f9fa;
padding: 20px;
text-align: center;
color: #666;
border-top: 1px solid #e0e0e0;
font-size: 0.9em;
}}
.progress-bar {{
width: 100%;
height: 8px;
background: #e0e0e0;
border-radius: 4px;
overflow: hidden;
margin-top: 10px;
}}
.progress-fill {{
height: 100%;
background: linear-gradient(90deg, #667eea, #764ba2);
transition: width 0.3s ease;
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>πŸ€– Data Dictionary Chatbot</h1>
<h2>Accuracy Analysis Report</h2>
<p>Generated on {timestamp}</p>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">Total Tests</div>
<div class="metric-value">{total}</div>
</div>
<div class="metric">
<div class="metric-label">Passed</div>
<div class="metric-value" style="color: #22c55e;">{passed}</div>
</div>
<div class="metric">
<div class="metric-label">Failed</div>
<div class="metric-value" style="color: #ef4444;">{failed}</div>
</div>
<div class="metric">
<div class="metric-label">Average Score</div>
<div class="metric-value">{avg_score:.2%}</div>
</div>
<div class="metric">
<div class="metric-label">Pass Rate</div>
<div class="metric-value" style="color: {status_color};">{pass_rate:.1%}</div>
<div class="progress-bar">
<div class="progress-fill" style="width: {pass_rate * 100}%"></div>
</div>
</div>
<div class="metric">
<div class="overall-status">{status_text}</div>
</div>
</div>
<div class="content">
<div class="section">
<div class="section-title">πŸ“Š Summary</div>
<div class="summary">
<div class="summary-item">
<span class="summary-label">Overall Assessment:</span>
<span class="summary-value">{self._get_assessment_text(pass_rate)}</span>
</div>
<div class="summary-item">
<span class="summary-label">Success Rate:</span>
<span class="summary-value">{pass_rate:.1%} ({passed}/{total})</span>
</div>
<div class="summary-item">
<span class="summary-label">Average Quality Score:</span>
<span class="summary-value">{avg_score:.2f}/1.00</span>
</div>
</div>
</div>
<div class="section">
<div class="section-title">πŸ§ͺ Test Results</div>
{self._generate_test_results_html(batch_analysis.get("analyses", []))}
</div>
</div>
<div class="footer">
<p>Generated by Data Dictionary Chatbot Testing Framework</p>
<p>For detailed test case information, refer to test_cases.json</p>
</div>
</div>
</body>
</html>
"""
return html
def _generate_markdown_content(self, batch_analysis: Dict[str, Any]) -> str:
"""Generate Markdown content for report."""
timestamp = self.timestamp.strftime("%Y-%m-%d %H:%M:%S")
total = batch_analysis.get("total_tests", 0)
passed = batch_analysis.get("passed_tests", 0)
failed = batch_analysis.get("failed_tests", 0)
avg_score = batch_analysis.get("average_score", 0)
pass_rate = batch_analysis.get("pass_rate", 0)
status_emoji = "βœ…" if pass_rate >= 0.8 else "⚠️" if pass_rate >= 0.6 else "❌"
md = f"""# Data Dictionary Chatbot - Accuracy Report
**Generated:** {timestamp}
{status_emoji} **Overall Status:** {self._get_assessment_text(pass_rate)}
---
## Summary Metrics
| Metric | Value |
|--------|-------|
| **Total Tests** | {total} |
| **Passed** | {passed} βœ… |
| **Failed** | {failed} ❌ |
| **Average Score** | {avg_score:.2%} |
| **Pass Rate** | {pass_rate:.1%} |
---
## Key Findings
### Strengths
"""
# Add strengths/weaknesses analysis
md += self._analyze_validation_patterns(batch_analysis)
md += f"""
---
## Detailed Test Results
"""
# Add individual test results
for analysis in batch_analysis.get("analyses", []):
status = "βœ… PASSED" if analysis["overall_passed"] else "❌ FAILED"
md += f"""### {analysis['test_name']} ({analysis['test_id']})
- **Status:** {status}
- **Overall Score:** {analysis['overall_score']:.2%}
**Validations:**
"""
for validator_name, validator_result in analysis.get("validations", {}).items():
v_status = "βœ…" if validator_result.get("passed", False) else "❌"
v_score = validator_result.get("score", 0)
md += f"- {v_status} **{validator_name.title()}**: {v_score:.2%}\n"
if validator_result.get("issues"):
for issue in validator_result["issues"]:
md += f" - ⚠️ {issue}\n"
md += "\n"
md += f"""---
## Recommendations
{self._generate_recommendations(batch_analysis)}
---
**Report Generated:** {timestamp}
"""
return md
def _generate_test_results_html(self, analyses: List[Dict[str, Any]]) -> str:
"""Generate HTML for individual test results."""
html = ""
for analysis in analyses:
passed = analysis["overall_passed"]
score = analysis["overall_score"]
status_class = "passed" if passed else "failed"
score_class = self._get_score_class(score)
html += f"""
<div class="test-result {status_class}">
<div class="test-header">
<div>
<div class="test-name">{'βœ…' if passed else '❌'} {analysis['test_name']}</div>
<div class="test-id">{analysis['test_id']}</div>
</div>
<div class="test-score {score_class}">{score:.0%}</div>
</div>
<div class="validator-results">
"""
for validator_name, validator_result in analysis.get("validations", {}).items():
v_status = validator_result.get("passed", False)
v_class = "passed" if v_status else "failed"
v_score = validator_result.get("score", 0)
html += f"""
<div class="validator {v_class}">
<div class="validator-name">{'βœ…' if v_status else '❌'} {validator_name}</div>
<div class="validator-score">Score: {v_score:.2%}</div>
"""
if validator_result.get("issues"):
html += '<div class="validator-issues">'
html += '<ul class="issues-list">'
for issue in validator_result["issues"]:
html += f'<li>{issue}</li>'
html += '</ul></div>'
html += '</div>'
html += """
</div>
</div>
"""
return html
@staticmethod
def _get_score_class(score: float) -> str:
"""Get CSS class for score."""
if score >= 0.9:
return "excellent"
elif score >= 0.75:
return "good"
elif score >= 0.5:
return "fair"
else:
return "poor"
@staticmethod
def _get_assessment_text(pass_rate: float) -> str:
"""Get assessment text based on pass rate."""
if pass_rate >= 0.95:
return "Excellent - App is production-ready πŸš€"
elif pass_rate >= 0.85:
return "Good - App works well with minor improvements needed βœ…"
elif pass_rate >= 0.70:
return "Fair - App functions but needs improvements ⚠️"
elif pass_rate >= 0.50:
return "Poor - Significant issues need addressing ❌"
else:
return "Critical - Major rework required 🚨"
@staticmethod
def _analyze_validation_patterns(batch_analysis: Dict[str, Any]) -> str:
"""Analyze patterns in validation results."""
analyses = batch_analysis.get("analyses", [])
# Count validation successes
validation_success = {}
for analysis in analyses:
for validator_name, validator_result in analysis.get("validations", {}).items():
if validator_name not in validation_success:
validation_success[validator_name] = {"passed": 0, "total": 0}
validation_success[validator_name]["total"] += 1
if validator_result.get("passed", False):
validation_success[validator_name]["passed"] += 1
# Generate text
text = ""
for validator_name, stats in sorted(validation_success.items(),
key=lambda x: x[1]["passed"]/max(x[1]["total"], 1),
reverse=True):
rate = stats["passed"] / stats["total"] if stats["total"] > 0 else 0
text += f"- **{validator_name.title()}**: {stats['passed']}/{stats['total']} tests passed ({rate:.0%})\n"
return text or "No validation data available"
@staticmethod
def _generate_recommendations(batch_analysis: Dict[str, Any]) -> str:
"""Generate recommendations based on analysis."""
pass_rate = batch_analysis.get("pass_rate", 0)
recommendations = []
if pass_rate >= 0.9:
recommendations.append("βœ… Application is performing excellently. Continue monitoring and iterating.")
elif pass_rate >= 0.75:
recommendations.append("⚠️ Address failing test cases before production deployment.")
elif pass_rate >= 0.5:
recommendations.append("⚠️ Significant improvements needed in citation accuracy and hallucination detection.")
else:
recommendations.append("🚨 Critical issues detected. Review retrieval and LLM prompt engineering.")
recommendations.extend([
"- Ensure all recommended columns are verified against loaded dictionaries",
"- Review system prompts to improve citation formatting consistency",
"- Monitor Area Insights geographic accuracy for regional data",
"- Consider fine-tuning retrieval parameters for better relevance",
"- Implement continuous testing in CI/CD pipeline"
])
return "\n".join(recommendations)