added new module 'chat.py'

This commit is contained in:
juk0de 2023-08-24 16:49:54 +02:00
parent a010a6f5d0
commit cb0a90f72a

44
chatmastermind/chat.py Normal file
View File

@ -0,0 +1,44 @@
"""
Module implementing the 'Chat' class and functions for managing a chat history.
"""
import pathlib
from dataclasses import dataclass
from typing import TypeVar, Type, Optional
from .message import Message, MessageFilter, MessageError
ChatInst = TypeVar('ChatInst', bound='Chat')
class ChatError(Exception):
pass
@dataclass
class Chat:
"""
Class containing a complete chat history.
"""
messages: list[Message]
@classmethod
def from_dir(cls: Type[ChatInst],
path: pathlib.Path,
glob: Optional[str] = None,
mfilter: Optional[MessageFilter] = None) -> ChatInst:
"""
Create a Chat instance from the message in the given directory.
If glob is specified, files will be filtered using path.glob(),
otherwise it uses path.iterdir(). Messages are created using
Message.from_file() and the optional MessageFilter.
"""
messages: list[Message] = []
file_iter = path.glob(glob) if glob else path.iterdir()
for file_path in file_iter:
if file_path.is_file():
try:
message = Message.from_file(file_path, mfilter)
if message:
messages.append(message)
except MessageError as e:
print(f"Error processing message in '{file_path}': {str(e)}")
return cls(messages)