Skip to content

Commit

Permalink
Merge pull request #19 from ttpss930141011/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
ttpss930141011 authored Apr 25, 2024
2 parents 7c2a763 + 0c84225 commit f5667f0
Show file tree
Hide file tree
Showing 32 changed files with 575 additions and 279 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:
- name: Set up Python 3.11
uses: actions/setup-python@v3
with:
python-version: "3.11.8"
python-version: "3.11.4"

- name: Cache dependencies
id: cache
Expand Down
2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

219 changes: 198 additions & 21 deletions .idea/workspace.xml

Large diffs are not rendered by default.

11 changes: 2 additions & 9 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
""" Flask PostgreSQL Process Handler
"""


from src.app.flask_postgresql.configs import Config
from src.app.flask_postgresql.create_flask_postgresql_app import (
create_flask_postgresql_app,
)
from src.infrastructure.loggers.logger_default import LoggerDefault

logger = LoggerDefault()

from src.app.flask_postgresql.create_flask_postgresql_app import create_flask_postgresql_app

if __name__ == "__main__":
app = create_flask_postgresql_app(Config, logger)
app = create_flask_postgresql_app(Config)
app.run(host="0.0.0.0", port=Config.PORT, debug=True)
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/app/flask_postgresql/api/blueprints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
from .main import blueprint as main_blueprint


def setup_blueprints(app: Flask) -> None:
def setup_blueprints(app: Flask) -> Flask:
"""
Register the necessary blueprints for the Flask app.
Parameters:
app (Flask): The Flask app instance.
Returns:
None: This function does not return anything.
None: The Flask app instance with the blueprints registered.
"""
app.register_blueprint(callback_blueprint)
app.register_blueprint(main_blueprint)
Expand Down
2 changes: 1 addition & 1 deletion src/app/flask_postgresql/api/blueprints/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
@blueprint.route("/callback", methods=["POST"])
def callback_blueprint():
"""Function printing python version."""
logger: LoggerInterface = current_app.config["logger"]
logger: LoggerInterface = current_app.config["container"].resolve("logger")
signature = request.headers["X-Line-Signature"]
body = request.get_data(as_text=True)

Expand Down
20 changes: 20 additions & 0 deletions src/app/flask_postgresql/api/container.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from flask import Flask, g
from src.infrastructure.container.container import Container
from src.infrastructure.repositories.agent_chain.agent_chain_in_memory_repository import (
AgentExecutorInMemoryRepository,
)
from src.infrastructure.repositories.window import WindowPostgresqlRepository
from src.infrastructure.loggers.logger_default import LoggerDefault


def setup_container(app: Flask) -> Flask:
"""Setup Container for the app"""
container = Container()

container.register("agent_repository", AgentExecutorInMemoryRepository())
container.register("window_repository", WindowPostgresqlRepository())
container.register("logger", LoggerDefault())

app.config["container"] = container

return app
4 changes: 2 additions & 2 deletions src/app/flask_postgresql/api/error_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ def format_marshmallow_validation_error(errors: Dict):
return errors_message


def setup_error_handler(app: Flask) -> None:
def setup_error_handler(app: Flask) -> Flask:
"""
Function that will register all the specified error handlers for the app
"""

logger: LoggerInterface = app.config["logger"]
logger: LoggerInterface = app.config["container"].resolve("logger")

def error_handler(error):
logger.log_exception("exception of type {} occurred".format(type(error)))
Expand Down
37 changes: 16 additions & 21 deletions src/app/flask_postgresql/api/event_handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,43 +3,38 @@
from flask import current_app
from linebot.v3 import WebhookHandler
from linebot.v3.messaging import Configuration
from linebot.v3.webhooks import FileMessageContent, MessageEvent, TextMessageContent
from linebot.v3.webhooks import MessageEvent, TextMessageContent

from src.app.flask_postgresql.api.event_handlers.file_event_handler import FileEventHandler
from src.app.flask_postgresql.api.event_handlers.text_event_handler import TextEventHandler
from src.app.flask_postgresql.api.response import create_response
from src.app.flask_postgresql.configs import Config
from src.infrastructure.repositories.agent_chain.agent_chain_in_memory_repository import (
AgentExecutorInMemoryRepository,
)
from src.infrastructure.container.container import Container

handler = WebhookHandler(Config.CHANNEL_SECRET)
configuration = Configuration(access_token=Config.CHANNEL_ACCESS_TOKEN)
agent_repository = AgentExecutorInMemoryRepository()


@handler.add(MessageEvent, message=TextMessageContent)
def handle_text_message(event: MessageEvent):
handler = TextEventHandler(
logger=current_app.config["logger"],
agent_repository=agent_repository,
)
handler.get_event_info(event)
result = handler.execute()
container: Container = current_app.config["container"]
text_handler = TextEventHandler(container)
text_handler.get_event_info(event)
result = text_handler.execute()

return create_response(configuration, event.reply_token, result)


@handler.add(MessageEvent, message=FileMessageContent)
def handle_file_message(event: MessageEvent):
handler = FileEventHandler(
logger=current_app.config["logger"],
agent_repository=agent_repository,
configuration=configuration,
)
result = handler.execute(event)

return create_response(configuration, event.reply_token, result)
# @handler.add(MessageEvent, message=FileMessageContent)
# def handle_file_message(event: MessageEvent):
# file_handler = FileEventHandler(
# logger=current_app.config["logger"],
# agent_repository=agent_repository,
# configuration=configuration,
# )
# result = file_handler.execute(event)
#
# return create_response(configuration, event.reply_token, result)


__all__ = ["handler"]
41 changes: 23 additions & 18 deletions src/app/flask_postgresql/api/event_handlers/event_handler.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,44 @@
""" This module implements the event handler for text message events.
"""
from abc import abstractmethod
from typing import Dict
from typing import Dict, cast

from linebot.v3.webhooks import MessageEvent

from src.app.flask_postgresql.configs import Config
from src.app.flask_postgresql.interfaces.event_handler_interface import EventHandlerInterface
from src.app.flask_postgresql.presenters.window_presenter import WindowPresenter
from src.infrastructure.repositories.agent_chain.agent_chain_in_memory_repository import (
AgentExecutorInMemoryRepository,
)
from src.infrastructure.repositories.window.window_postgresql_repository import (
WindowPostgresqlRepository,
)
from src.infrastructure.container.container import Container
from src.interactor.dtos.event_dto import EventInputDto
from src.interactor.dtos.window_dtos import CreateWindowInputDto, GetWindowInputDto
from src.interactor.interfaces.logger.logger import LoggerInterface
from src.interactor.interfaces.repositories.agent_executor_repository import AgentExecutorRepositoryInterface
from src.interactor.interfaces.repositories.window_repository import WindowRepositoryInterface
from src.interactor.use_cases.window.create_window import CreateWindowUseCase
from src.interactor.use_cases.window.get_window import GetWindowUseCase


class EventHandler(EventHandlerInterface):
def __init__(self, logger: LoggerInterface, agent_repository: AgentExecutorInMemoryRepository):
self.logger = logger
self.agent_repository = agent_repository
self.input_dto: EventInputDto
def __init__(self, container: Container):
self.container = container
self.logger = cast(LoggerInterface, container.resolve("logger"))
self.agent_repository = cast(AgentExecutorRepositoryInterface, container.resolve("agent_repository"))
self.window_repository = cast(WindowRepositoryInterface, container.resolve("window_repository"))
self.input_dto = None
self.event = None

def get_event_info(self, event: MessageEvent):
if event.source.type == "user":
"""
Retrieves the information of an event.
"""
self.event = event
source_type = event.source.type

if source_type == "user":
window_id = event.source.user_id
elif event.source.type == "group":
elif source_type == "group":
window_id = event.source.group_id
elif event.source.type == "room":
elif source_type == "room":
window_id = event.source.room_id
else:
raise ValueError("Invalid event source type")
Expand All @@ -45,6 +51,7 @@ def get_event_info(self, event: MessageEvent):
self.input_dto = EventInputDto(
window=self.get_window_info(window_id=window_id),
user_input=user_input,
source_type=source_type,
)

def get_window_info(self, window_id: str) -> Dict:
Expand All @@ -66,9 +73,8 @@ def _get_window_info(self, window_id: str):
:return: The result of executing the use case.
"""
repository = WindowPostgresqlRepository()
presenter = WindowPresenter()
use_case = GetWindowUseCase(presenter=presenter, repository=repository, logger=self.logger)
use_case = GetWindowUseCase(presenter=presenter, repository=self.window_repository, logger=self.logger)
get_window_input_dto = GetWindowInputDto(window_id)
result = use_case.execute(get_window_input_dto)
return result
Expand All @@ -80,7 +86,6 @@ def _create_window_info(self, window_id: str):
Returns:
The result of the create window use case execution.
"""
repository = WindowPostgresqlRepository()
presenter = WindowPresenter()
create_window_input_dto = CreateWindowInputDto(
window_id=window_id,
Expand All @@ -90,7 +95,7 @@ def _create_window_info(self, window_id: str):
temperature=0,
)
use_case = CreateWindowUseCase(
presenter=presenter, repository=repository, logger=self.logger
presenter=presenter, repository=self.window_repository, logger=self.logger
)
result = use_case.execute(create_window_input_dto)
return result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,18 @@

from src.app.flask_postgresql.api.event_handlers.event_handler import EventHandler
from src.app.flask_postgresql.presenters.message_reply_presenter import EventPresenter
from src.infrastructure.container.container import Container
from src.interactor.dtos.event_dto import EventInputDto
from src.interactor.use_cases.message.create_message_reply import CreateMessageReplyUseCase


class TextEventHandler(EventHandler):
def __init__(self, logger, agent_repository):
self.logger = logger
self.agent_repository = agent_repository
def __init__(self, container: Container):
super().__init__(container)
self.input_dto: EventInputDto

def execute(self):
presenter = EventPresenter()
use_case = CreateMessageReplyUseCase(
presenter=presenter,
repository=self.agent_repository,
logger=self.logger,
)
use_case = CreateMessageReplyUseCase(presenter=presenter, container=self.container)
result = use_case.execute(self.input_dto)
return result
6 changes: 3 additions & 3 deletions src/app/flask_postgresql/api/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
from linebot.v3.messaging.models.message import Message


def create_response(
configuration: Configuration, reply_token: str, messages: List[Message]
) -> ApiResponse:
def create_response(configuration: Configuration, reply_token: str, messages: List[Message]) -> ApiResponse:
if not messages:
return
with ApiClient(configuration) as api_client:
line_bot_api = MessagingApi(api_client)

Expand Down
6 changes: 3 additions & 3 deletions src/app/flask_postgresql/create_flask_postgresql_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@
from flask import Flask

from src.app.flask_postgresql.api.blueprints import setup_blueprints
from src.app.flask_postgresql.api.container import setup_container
from src.app.flask_postgresql.api.error_handler import setup_error_handler
from src.app.flask_postgresql.api.request_context import setup_request_context
from src.infrastructure.databases.sql_alchemy import setup_sqlalchemy
from src.interactor.interfaces.logger.logger import LoggerInterface


def create_flask_postgresql_app(config, logger: LoggerInterface) -> Flask:
def create_flask_postgresql_app(config) -> Flask:
"""Create Main Flask PostgreSQL app"""
app = Flask(__name__)
app.config.from_object(config)
app.config["logger"] = logger
app = setup_container(app)
app = setup_blueprints(app)
app = setup_sqlalchemy(app)
app = setup_error_handler(app)
Expand Down
12 changes: 4 additions & 8 deletions src/app/flask_postgresql/create_flask_postgresql_app_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,17 @@
from flask.testing import FlaskClient

from src.app.flask_postgresql.configs import Config
from src.infrastructure.loggers.logger_default import LoggerDefault

with mock.patch("sqlalchemy.create_engine") as mock_create_engine, mock.patch(
"langchain.utilities.SerpAPIWrapper"
"langchain.utilities.SerpAPIWrapper"
) as mock_sessionmaker:
from .create_flask_postgresql_app import create_flask_postgresql_app


logger = LoggerDefault()


@pytest.fixture(name="flask_postgresql_app")
def fixture_flask_postgresql_app():
"""Fixture for flask app with blueprint"""
app: Flask = create_flask_postgresql_app(Config, logger)
app: Flask = create_flask_postgresql_app(Config)
app.config.update(
{
"TESTING": True,
Expand Down Expand Up @@ -56,8 +52,8 @@ def test_request_window(mocker, client_flask_postgresql_app: FlaskClient):


def test_request_window_wrong_url_error(
mocker,
client_flask_postgresql_app,
mocker,
client_flask_postgresql_app,
):
"""Test request example"""
headers_data = {"X-Line-Signature": "test"}
Expand Down
15 changes: 15 additions & 0 deletions src/infrastructure/container/container.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Container:
def __init__(self):
self._dependencies = {}

def register(self, key, dependency):
self._dependencies[key] = dependency

def resolve(self, key):
return self._dependencies[key]

def __getitem__(self, key):
return self.resolve(key)

def __setitem__(self, key, dependency):
self.register(key, dependency)
Loading

0 comments on commit f5667f0

Please sign in to comment.