🔍 Code Extractor

class TextSection

Maturity: 51

A dataclass representing a text section entity with versioning, chat interface, data analysis capabilities, and metadata management.

File:
/tf/active/vicechatdev/vice_ai/models.py
Lines:
318 - 422
Complexity:
moderate

Purpose

TextSection is the central entity of the system that represents a structured text document section. It manages content versioning, integrates with chat interfaces for AI-assisted content generation, supports data analysis sessions, and maintains comprehensive metadata including ownership, timestamps, tags, and references. It serves as the primary data model for document sections with full lifecycle management from draft to published states.

Source Code

class TextSection:
    """Core TextSection model - the central entity of the system"""
    id: str
    owner: str  # User email/ID
    title: str
    section_type: SectionType
    level: int = 1
    
    # Content and versioning
    current_content: str = ""
    current_version_id: str = ""
    status: ContentStatus = ContentStatus.DRAFT
    
    # Timestamps
    created_at: datetime = None
    updated_at: datetime = None
    
    # Chat interface
    chat_configuration: ChatConfiguration = None
    chat_messages: List[ChatMessage] = None
    chat_session_id: str = None  # Link to ChatSession
    
    # References from last AI generation
    last_references: List[Dict] = None
    
    # Data Analysis - for DATA_ANALYSIS section type
    analysis_session_id: str = None  # Link to DataAnalysisSession
    
    # Metadata
    tags: List[str] = None
    metadata: Dict[str, Any] = None
    
    def __post_init__(self):
        if self.created_at is None:
            self.created_at = datetime.now()
        if self.updated_at is None:
            self.updated_at = datetime.now()
        if self.chat_configuration is None:
            self.chat_configuration = ChatConfiguration(
                selected_collections=[],
                uploaded_documents=[]
            )
        if self.chat_messages is None:
            self.chat_messages = []
        if self.last_references is None:
            self.last_references = []
        if self.tags is None:
            self.tags = []
        if self.metadata is None:
            self.metadata = {}
        if self.current_version_id == "":
            self.current_version_id = str(uuid.uuid4())
    
    @property
    def content(self) -> str:
        """Alias for current_content for backward compatibility"""
        return self.current_content
    
    @content.setter
    def content(self, value: str):
        """Setter for content property"""
        self.current_content = value
    
    def to_dict(self) -> Dict:
        return {
            'id': self.id,
            'owner': self.owner,
            'title': self.title,
            'section_type': self.section_type.value,
            'level': self.level,
            'current_content': self.current_content,
            'current_version_id': self.current_version_id,
            'status': self.status.value,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'chat_configuration': self.chat_configuration.to_dict(),
            'chat_messages': [msg.to_dict() for msg in self.chat_messages],
            'chat_session_id': self.chat_session_id,
            'last_references': self.last_references,
            'analysis_session_id': self.analysis_session_id,
            'tags': self.tags,
            'metadata': self.metadata
        }
    
    @classmethod
    def from_dict(cls, data: Dict) -> 'TextSection':
        return cls(
            id=data['id'],
            owner=data['owner'],
            title=data['title'],
            section_type=SectionType(data['section_type']),
            level=data.get('level', 1),
            current_content=data.get('current_content', ''),
            current_version_id=data.get('current_version_id', str(uuid.uuid4())),
            status=ContentStatus(data.get('status', ContentStatus.DRAFT.value)),
            created_at=datetime.fromisoformat(data['created_at']),
            updated_at=datetime.fromisoformat(data['updated_at']),
            chat_configuration=ChatConfiguration.from_dict(data.get('chat_configuration', {})),
            chat_messages=[ChatMessage.from_dict(msg) for msg in data.get('chat_messages', [])],
            chat_session_id=data.get('chat_session_id'),
            last_references=data.get('last_references', []),
            analysis_session_id=data.get('analysis_session_id'),
            tags=data.get('tags', []),
            metadata=data.get('metadata', {})
        )

Parameters

Name Type Default Kind
bases - -

Parameter Details

id: Unique identifier string for the text section

owner: User email or ID string identifying the section owner

title: Display title string for the section

section_type: SectionType enum value indicating the type of section (e.g., text, data analysis)

level: Integer representing hierarchical level of the section (default: 1)

current_content: String containing the current text content of the section (default: empty string)

current_version_id: UUID string identifying the current version (auto-generated if empty)

status: ContentStatus enum value indicating the section's state (default: DRAFT)

created_at: datetime object for creation timestamp (auto-set to now if None)

updated_at: datetime object for last update timestamp (auto-set to now if None)

chat_configuration: ChatConfiguration object containing chat interface settings (auto-initialized if None)

chat_messages: List of ChatMessage objects representing conversation history (auto-initialized to empty list if None)

chat_session_id: Optional string linking to an associated ChatSession

last_references: List of dictionaries containing references from the last AI generation (auto-initialized to empty list if None)

analysis_session_id: Optional string linking to a DataAnalysisSession for DATA_ANALYSIS section types

tags: List of string tags for categorization (auto-initialized to empty list if None)

metadata: Dictionary for storing arbitrary key-value metadata (auto-initialized to empty dict if None)

Return Value

Instantiation returns a TextSection object with all attributes initialized. The to_dict() method returns a dictionary representation with all fields serialized (enums to values, datetimes to ISO format strings). The from_dict() class method returns a new TextSection instance reconstructed from a dictionary. The content property returns the current_content string.

Class Interface

Methods

__post_init__(self) -> None

Purpose: Initializes default values for optional attributes after dataclass initialization

Returns: None - modifies instance attributes in place

@property content(self) -> str property

Purpose: Property getter providing backward-compatible access to current_content

Returns: String containing the current content of the section

@content.setter content(self, value: str) -> None property

Purpose: Property setter for updating current_content through the content alias

Parameters:

  • value: String value to set as the current content

Returns: None - updates current_content attribute

to_dict(self) -> Dict

Purpose: Serializes the TextSection instance to a dictionary representation

Returns: Dictionary with all attributes serialized, including enum values converted to strings, datetimes to ISO format, and nested objects converted via their to_dict() methods

@classmethod from_dict(cls, data: Dict) -> TextSection

Purpose: Class method to deserialize a dictionary into a TextSection instance

Parameters:

  • data: Dictionary containing serialized TextSection data with keys matching attribute names

Returns: New TextSection instance reconstructed from the dictionary data with proper type conversions

Attributes

Name Type Description Scope
id str Unique identifier for the text section instance
owner str User email or ID identifying the section owner instance
title str Display title of the section instance
section_type SectionType Enum indicating the type of section (e.g., text, data analysis) instance
level int Hierarchical level of the section (default: 1) instance
current_content str Current text content of the section instance
current_version_id str UUID identifying the current version of the content instance
status ContentStatus Enum indicating the section's status (DRAFT, PUBLISHED, etc.) instance
created_at datetime Timestamp when the section was created instance
updated_at datetime Timestamp of the last update to the section instance
chat_configuration ChatConfiguration Configuration object for chat interface settings including selected collections and uploaded documents instance
chat_messages List[ChatMessage] List of chat messages representing conversation history instance
chat_session_id str Optional identifier linking to an associated ChatSession instance
last_references List[Dict] List of reference dictionaries from the last AI content generation instance
analysis_session_id str Optional identifier linking to a DataAnalysisSession for DATA_ANALYSIS section types instance
tags List[str] List of string tags for categorization and search instance
metadata Dict[str, Any] Dictionary for storing arbitrary key-value metadata instance

Dependencies

  • uuid
  • datetime
  • typing
  • dataclasses

Required Imports

import uuid
from datetime import datetime
from typing import List, Dict, Any
from dataclasses import dataclass

Usage Example

# Create a new text section
from datetime import datetime

section = TextSection(
    id='section-123',
    owner='user@example.com',
    title='Introduction',
    section_type=SectionType.TEXT,
    level=1
)

# Update content
section.content = 'This is the introduction text.'
section.updated_at = datetime.now()

# Add tags
section.tags.append('introduction')
section.tags.append('chapter-1')

# Add metadata
section.metadata['word_count'] = 100

# Convert to dictionary for storage
data = section.to_dict()

# Reconstruct from dictionary
restored_section = TextSection.from_dict(data)

# Access content via property
print(restored_section.content)

# Update status
section.status = ContentStatus.PUBLISHED

Best Practices

  • Always use the from_dict() class method when deserializing from storage to ensure proper type conversion
  • Update the updated_at timestamp whenever modifying content or other significant attributes
  • Use the content property for backward compatibility instead of directly accessing current_content
  • Initialize with required fields (id, owner, title, section_type) and let __post_init__ handle optional fields
  • Generate a new current_version_id when creating a new version of the content
  • Ensure SectionType and ContentStatus enums are properly defined before instantiation
  • Use chat_session_id and analysis_session_id to link to external session entities
  • Store structured data in metadata dictionary for extensibility without schema changes
  • The __post_init__ method automatically initializes None values, so explicit initialization is optional
  • When updating status from DRAFT to PUBLISHED, consider creating a new version_id

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class TextSectionVersion 81.5% similar

    A dataclass representing a single version in the history of a text section's content, tracking changes, authorship, and timestamps.

    From: /tf/active/vicechatdev/vice_ai/models.py
  • class TextSectionService 79.3% similar

    Service class for managing TextSection entities, providing CRUD operations, versioning, chat functionality, and search capabilities.

    From: /tf/active/vicechatdev/vice_ai/services.py
  • class DocumentSection_v1 76.7% similar

    A dataclass representing a reference to a section (TextSection or DataSection) within a document structure, supporting hierarchical organization and section type differentiation.

    From: /tf/active/vicechatdev/vice_ai/models.py
  • class DocumentSection 76.6% similar

    A class representing a section within a complex document, supporting hierarchical structure with headers, text content, and references.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • class ChatSession_v1 73.7% similar

    A dataclass representing a chat session associated with a specific text section in a document, managing conversation messages, context, and references.

    From: /tf/active/vicechatdev/vice_ai/models.py
← Back to Browse