ramyro-report 2.0.0a1
AI Report Generation Module - Professional HTML and PDF report generation with component-based architecture
Requires Python: >=3.9

# Ramyro Report - AI Report Generation Module

A production-ready Python module for generating professional reports in both HTML and PDF formats. Built with performance, maintainability, and extensibility in mind.

## 🚀 Features

- **Dual Output Formats**: Generate reports in both HTML (Jinja2) and PDF (ReportLab)
- **Component-Based Architecture**: Modular, reusable components for different content types
- **Responsive Layouts**: Multi-column layouts with intelligent pagination
- **Professional Styling**: Consistent styling across HTML and PDF outputs
- **Type Safety**: Full type hints and comprehensive error handling
- **Production Ready**: Robust error handling, logging, and resource management

## 📋 Requirements

- Python 3.9+
- Dependencies: `jinja2`, `reportlab`, `numpy`, `matplotlib`, `pillow`

## 🏗️ Architecture Overview

The system is built around a component-based architecture where each piece of content is a renderable component:

```
Report (Main Container)
├── Section (Content Groups)
│   └── Block (Layout Container)
│       ├── Paragraph (Text)
│       ├── Table (Data)
│       ├── Figure (Images)
│       ├── List (Bulleted/Numbered)
│       └── Spacing (Layout Control)
```

## 🎯 Quick Start

### Basic Report Creation

```python
from src.report import Report
from src.components import Section, Block, Paragraph

# Create a report
report = Report(
    title="Patient Report",
    metadata={"patient_id": "P-123", "age": 35},
    font_family="Arial, sans-serif",
    font_size_pt=12
)

# Add content
section = Section("Findings")
block = Block(n_cols=2, widths=["60%", "40%"])
block.add_left(Paragraph("Left column content"))
block.add_right(Paragraph("Right column content"))
section.add_block(block)

report.add_section(section)

# Generate outputs
report.save("report.html")  # HTML output
report.save("report.pdf")   # PDF output
```

## 📚 Component Reference

### 1. Report Class

The main container that orchestrates rendering and manages the overall report structure.

```python
report = Report(
    title="Report Title",
    metadata={"key": "value"},
    font_family="Arial, sans-serif",
    font_size_pt=12,
    pdf_font_family="Helvetica",
    pdf_font_bold="Helvetica-Bold",
    pdf_font_italic="Helvetica-Oblique"
)
```

**Key Methods:**
- `add_section(section)`: Add a section to the report
- `render_html()`: Generate HTML string
- `render_pdf(filename)`: Generate PDF file
- `save(filepath)`: Save in appropriate format based on file extension

### 2. Section Component

Groups related content blocks with a title header.

```python
section = Section("Section Title")
section.add_block(block)
```

**Features:**
- Automatic title bar rendering
- Consistent spacing between sections
- Page break handling for PDF

### 3. Block Component

Arranges components in columns with configurable layouts.

```python
# Single column
block = Block(n_cols=1, widths="100%", aligns="center")

# Two columns
block = Block(n_cols=2, widths=["60%", "40%"], aligns=["left", "right"])

# Three columns with custom widths
block = Block(n_cols=3, widths=["25%", "50%", "25%"], aligns=["left", "center", "right"])
```

**Column Management:**
- `add_to_col(col_index, *components)`: Add to specific column
- `add_left(*components)`: Add to leftmost column
- `add_right(*components)`: Add to rightmost column

**Layout Features:**
- Automatic width normalization
- Intelligent pagination coordination
- Column alignment support

### 4. Paragraph Component

Renders styled text with various formatting options.

```python
paragraph = Paragraph(
    text="Your text here",
    color="#FF0000",        # Hex color or named color
    bold=True,              # Bold text
    italic=False,           # Italic text
    underline=True,         # Underlined text
    indent=20               # Left margin in pixels
)
```

**Styling Options:**
- **Colors**: Hex (#FF0000), named (red), or None for default
- **Font Styles**: Bold, italic, underline combinations
- **Indentation**: Boolean (20px) or custom pixel value
- **Text Processing**: Automatic word wrapping and hyphenation

### 5. Table Component

Renders tabular data with extensive styling options.

```python
table = Table(
    data=[
        ["Row 1", "Data A", "Data B"],
        ["Row 2", "Data C", "Data D"]
    ],
    col_headers=["Column 1", "Column 2", "Column 3"],
    row_headers=["Row 1", "Row 2"],
    width_mode="full_width",  # "fit_content" or "full_width"
    col_widths=["30%", "35%", "35%"],  # Percentage or proportional
    col_header_bg_color="#0b1f3a",
    col_header_text_color="#ffffff",
    text_align="center"
)
```

**Width Modes:**
- **`fit_content`**: Size columns to content (max 95% width)
- **`full_width`**: Use full available width with smart auto-proportional columns

**Column Width Options:**
- Percentages: `["30%", "40%", "30%"]`
- Proportional: `[1, 2, 1]` (25%, 50%, 25%)
- Auto: `None` (smart algorithm)

**Styling Features:**
- Separate header/row header colors
- Custom border colors
- Text alignment per column type
- Font size control

### 6. Figure Component

Renders images with labels and captions.

```python
figure = Figure(
    image_input="path/to/image.png",  # File path, PIL Image, numpy array, etc.
    label="Figure 1: Sample Image",
    caption="This is a sample image with description",
    width="80%",           # Percentage, pixels, or auto
    height="auto",          # Auto-calculated from aspect ratio
    text_align="center",    # Label/caption alignment
    autocrop=False          # Automatic background cropping
)
```

**Image Input Types:**
- File paths (PNG, JPG, etc.)
- PIL Image objects
- NumPy arrays
- Matplotlib figures
- Base64 data URIs
- BytesIO buffers

**Layout Control:**
- Responsive width (%, px, auto)
- Automatic height calculation
- Text alignment (left, center, right)
- Boundary constraint handling

### 7. List Component

Creates ordered or unordered lists.

```python
# Unordered list (bullets)
unordered_list = List(
    items=["Item 1", "Item 2", "Item 3"],
    ordered=False
)

# Ordered list (numbers)
ordered_list = List(
    items=["First", "Second", "Third"],
    ordered=True
)
```

**Features:**
- Automatic prefix generation (• or 1., 2., 3.)
- Consistent indentation
- Support for mixed content types

### 8. Spacing Component

Controls vertical and horizontal spacing between components.

```python
# Vertical spacing (multiple lines)
vertical_spacing = Spacing(amount=3, direction="vertical")

# Horizontal spacing (inline)
horizontal_spacing = Spacing(amount=5, direction="horizontal")
```

## 🔧 Advanced Usage

### Complex Multi-Column Layouts

```python
# Create a complex 3-column layout
block = Block(n_cols=3, widths=["25%", "50%", "25%"], aligns=["left", "center", "right"])

# Left column
block.add_to_col(0,
    Paragraph("Left Column", bold=True),
    Figure("left_image.png", label="Left Image", width="90%"),
    List(["Point 1", "Point 2"], ordered=False)
)

# Center column
block.add_to_col(1,
    Paragraph("Center Column", bold=True, color="blue"),
    Table(data=[[1, 2], [3, 4]], col_headers=["A", "B"]),
    Spacing(amount=2, direction="vertical")
)

# Right column
block.add_to_col(2,
    Paragraph("Right Column", bold=True, color="red"),
    Figure("right_image.png", label="Right Image", width="95%")
)

section.add_block(block)
```

### Custom Styling and Theming

```python
# Create a themed report
report = Report(
    title="Medical Report",
    font_family="Georgia, serif",
    font_size_pt=11,
    pdf_font_family="Times-Roman",
    pdf_font_bold="Times-Bold",
    pdf_font_italic="Times-Italic"
)

# Use consistent colors
MEDICAL_BLUE = "#2c5aa0"
MEDICAL_GRAY = "#666666"

table = Table(
    data=patient_data,
    col_header_bg_color=MEDICAL_BLUE,
    col_header_text_color="#ffffff",
    cell_bg_color="#f9f9f9",
    border_color=MEDICAL_GRAY
)
```

### Error Handling and Validation

```python
try:
    # Add components with validation
    if patient_data:
        table = Table(data=patient_data)
        section.add_block(Block().add_left(table))
    else:
        section.add_block(Block().add_left(Paragraph("No data available", italic=True)))
        
    report.add_section(section)
    report.save("output.pdf")
    
except ValueError as e:
    print(f"Validation error: {e}")
except RuntimeError as e:
    print(f"Rendering error: {e}")
```

## 📊 Performance Considerations

### Memory Management
- Images are automatically converted to base64 for HTML and optimized for PDF
- Large tables use row-level pagination to prevent memory issues
- Components are rendered on-demand during PDF generation

### Rendering Optimization
- HTML rendering uses efficient Jinja2 templating
- PDF rendering implements smart pagination with coordinated page breaks
- Column layouts use intelligent width calculations

### Best Practices
- Use `estimate_pdf_height()` for components that support it
- Implement `supports_internal_pagination` for complex components
- Use appropriate width modes for tables (fit_content vs full_width)

## 🧪 Testing and Development

### Running the Demo

```bash
cd tests
python comprehensive_demo.py
```

This generates both HTML and PDF outputs demonstrating all component features.

### Component Testing

```python
# Test individual components
from src.components import Paragraph, Table

# Test paragraph rendering
p = Paragraph("Test text", bold=True, color="red")
html = p.render_html()
print(html)

# Test table creation
t = Table(data=[["A", "B"], ["1", "2"]])
html = t.render_html()
print(html)
```

## 🚨 Common Issues and Solutions

### Table in Multi-Column Layout
**Issue**: Tables cannot be used in multi-column blocks
**Solution**: Use `n_cols=1` for blocks containing tables

### Image Rendering Issues
**Issue**: Images not displaying in PDF
**Solution**: Ensure image paths are correct and images are in supported formats

### Font Consistency
**Issue**: Different fonts in HTML vs PDF
**Solution**: Use consistent font families in Report constructor

### Pagination Problems
**Issue**: Content overlapping in PDF
**Solution**: Components should implement `estimate_pdf_height()` and `supports_internal_pagination`

## 🔮 Extending the System

### Creating Custom Components

```python
from src.components.component import Component

class CustomComponent(Component):
    def __init__(self, data):
        self.data = data
    
    def render_html(self, container_width_px=None):
        return f"<div>{self.data}</div>"
    
    def render_pdf(self, canvas, x, y, width):
        # PDF rendering logic
        return y - 20  # Return new y position
```

### Adding New Rendering Formats

Extend the Report class to support additional output formats:

```python
def render_markdown(self):
    """Render report to Markdown format."""
    # Implementation here
    pass
```

## 📝 Contributing

1. Follow the existing code style and patterns
2. Add comprehensive type hints
3. Include Google-style docstrings
4. Add error handling and validation
5. Update tests and documentation
6. Ensure backwards compatibility

## 📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🤝 Support

For questions, issues, or contributions:
- Check the comprehensive demo for usage examples
- Review component docstrings for detailed API information
- Ensure all dependencies are properly installed
- Test with the provided demo script

---

**Built with ❤️ for professional report generation**