From 8d50a9aafa931c5b007dc2418099797dacbdd825 Mon Sep 17 00:00:00 2001 From: pbrochar Date: Mon, 19 Feb 2024 18:51:51 +0100 Subject: [PATCH] Fix ruff --- blitz/api/blitz_api.py | 13 +---- blitz/cli/commands/start.py | 29 +++------- blitz/models/blitz/file.py | 28 +++------ blitz/ui/blitz_ui.py | 2 - blitz/ui/components/gpt_chat_components.py | 18 ++---- blitz/ui/components/header.py | 56 ++++++------------ blitz/ui/pages/dashboard.py | 33 +++-------- blitz/ui/pages/diagram.py | 9 +-- blitz/ui/pages/gpt_builder.py | 67 +++++++--------------- blitz/ui/pages/log.py | 1 - 10 files changed, 70 insertions(+), 186 deletions(-) diff --git a/blitz/api/blitz_api.py b/blitz/api/blitz_api.py index 8338572..9d38a95 100644 --- a/blitz/api/blitz_api.py +++ b/blitz/api/blitz_api.py @@ -91,10 +91,7 @@ def _create_crud_router(self, resource: BlitzResource) -> CRUDGenerator: # Rebuild the model to include forward ref types that was not available at the time of the model creation # We need to use the model AFTER the rebuild because if not, all the relationship and cie will not be set # correctly. - types_namespace = { - resource.model.__name__: resource.model - for resource in self.blitz_app.resources - } + types_namespace = {resource.model.__name__: resource.model for resource in self.blitz_app.resources} read_model.model_rebuild(_types_namespace=types_namespace) create_model.model_rebuild(_types_namespace=types_namespace) update_model.model_rebuild(_types_namespace=types_namespace) @@ -189,12 +186,8 @@ def create_blitz_api( warnings.simplefilter("ignore", category=SAWarning) BlitzAdmin(blitz_app).mount_to(blitz_api) - print( - "\n[bold yellow]This is still an alpha. Please do not use in production.[/bold yellow]" - ) - print( - "[bold yellow]Please report any issues on https://github.com/Paperz-org/blitz[/bold yellow]" - ) + print("\n[bold yellow]This is still an alpha. Please do not use in production.[/bold yellow]") + print("[bold yellow]Please report any issues on https://github.com/Paperz-org/blitz[/bold yellow]") print( "\n".join( ( diff --git a/blitz/cli/commands/start.py b/blitz/cli/commands/start.py index 0226afc..ed67382 100644 --- a/blitz/cli/commands/start.py +++ b/blitz/cli/commands/start.py @@ -24,20 +24,12 @@ def start_blitz( - blitz_app_name: Annotated[ - Optional[str], typer.Argument(help="Blitz app name") - ] = None, + blitz_app_name: Annotated[Optional[str], typer.Argument(help="Blitz app name")] = None, admin: Annotated[bool, typer.Option(help="Don't create admin.")] = True, - port: Annotated[ - int, typer.Option(help="Define the port of the server") - ] = get_settings().BLITZ_PORT, - config_route: Annotated[ - bool, typer.Option(help="Enable the blitz config route.") - ] = True, + port: Annotated[int, typer.Option(help="Define the port of the server")] = get_settings().BLITZ_PORT, + config_route: Annotated[bool, typer.Option(help="Enable the blitz config route.")] = True, hot_reload: Annotated[bool, typer.Option(help="Enable the hot reload.")] = True, - version: Annotated[ - Optional[str], typer.Option(help="Define the version of the app.") - ] = None, + version: Annotated[Optional[str], typer.Option(help="Define the version of the app.")] = None, ) -> None: blitz = BlitzCore() @@ -87,14 +79,7 @@ def start_blitz( log_level="info", ) server = uvicorn.Server(server_config) - ChangeReload( - server_config, target=server.run, sockets=[server_config.bind_socket()] - ).run() + ChangeReload(server_config, target=server.run, sockets=[server_config.bind_socket()]).run() else: - - blitz_api = create_blitz_api( - blitz_app, enable_config_route=config_route, admin=admin - ) - uvicorn.run( - blitz_api, host="localhost", port=port, log_config=None, log_level="warning" - ) + blitz_api = create_blitz_api(blitz_app, enable_config_route=config_route, admin=admin) + uvicorn.run(blitz_api, host="localhost", port=port, log_config=None, log_level="warning") diff --git a/blitz/models/blitz/file.py b/blitz/models/blitz/file.py index 858dc48..dd67a01 100644 --- a/blitz/models/blitz/file.py +++ b/blitz/models/blitz/file.py @@ -1,5 +1,5 @@ from typing import Any, ClassVar, NoReturn -from pydantic import BaseModel, Field, ValidationError, field_serializer +from pydantic import BaseModel, Field, field_serializer from blitz.models.blitz.config import BlitzAppConfig from blitz.models.blitz.resource import BlitzResourceConfig from pathlib import Path @@ -35,9 +35,7 @@ class FileType(StrEnum): RESOURCES_FIELD_NAME: ClassVar[str] = "resources" config: BlitzAppConfig - resources_configs: list[BlitzResourceConfig] = Field( - default=[], serialization_alias=RESOURCES_FIELD_NAME - ) + resources_configs: list[BlitzResourceConfig] = Field(default=[], serialization_alias=RESOURCES_FIELD_NAME) raw_file: dict[str, Any] = Field(exclude=True) path: Path | None = Field(default=None, exclude=True) file_type: FileType | None = Field(default=None, exclude=True) @@ -47,14 +45,10 @@ class FileType(StrEnum): # blitz_file.write(self.model_dump_json) @field_serializer("resources_configs") - def _serialize_resources_configs( - self, resources_configs: list[BlitzResourceConfig], _info: Any - ) -> dict[str, Any]: + def _serialize_resources_configs(self, resources_configs: list[BlitzResourceConfig], _info: Any) -> dict[str, Any]: serialized_resources_configs = {} for resource_config in resources_configs: - serialized_resources_configs[resource_config.name] = ( - resource_config.model_dump() - ) + serialized_resources_configs[resource_config.name] = resource_config.model_dump() return serialized_resources_configs @@ -82,23 +76,15 @@ def from_dict( resource_name: str resource_config: dict[str, Any] - for resource_name, resource_config in blitz_file.get( - cls.RESOURCES_FIELD_NAME, {} - ).items(): + for resource_name, resource_config in blitz_file.get(cls.RESOURCES_FIELD_NAME, {}).items(): settings_fields = {} fields = {} for field_name, field_value in resource_config.items(): if field_name.startswith(BlitzResourceConfig.Settings.FIELD_PREFIX): - settings_fields[ - field_name[len(BlitzResourceConfig.Settings.FIELD_PREFIX) :] - ] = field_value + settings_fields[field_name[len(BlitzResourceConfig.Settings.FIELD_PREFIX) :]] = field_value else: fields[field_name] = field_value - resources_configs.append( - BlitzResourceConfig( - name=resource_name, fields=fields, settings=settings_fields - ) - ) + resources_configs.append(BlitzResourceConfig(name=resource_name, fields=fields, settings=settings_fields)) return cls( config=blitz_file.get(cls.CONFIG_FIELD_NAME), diff --git a/blitz/ui/blitz_ui.py b/blitz/ui/blitz_ui.py index 0c7bdbc..2c689fc 100644 --- a/blitz/ui/blitz_ui.py +++ b/blitz/ui/blitz_ui.py @@ -33,8 +33,6 @@ def current_project(self, project: str) -> None: print(project) self._current_project = project - - @property def current_app(self) -> BlitzApp | None: return self._current_app diff --git a/blitz/ui/components/gpt_chat_components.py b/blitz/ui/components/gpt_chat_components.py index 858a901..132de9f 100644 --- a/blitz/ui/components/gpt_chat_components.py +++ b/blitz/ui/components/gpt_chat_components.py @@ -71,9 +71,9 @@ def action_buttons(self) -> None: if self._dialog is None: # TODO: handle error raise Exception - ui.button( - icon="file_download", color="transparent", on_click=self._dialog.open - ).props("dense flat size=xm color=grey") + ui.button(icon="file_download", color="transparent", on_click=self._dialog.open).props( + "dense flat size=xm color=grey" + ) def download_dialog(self) -> None: with ui.dialog() as self._dialog, ui.card().classes("w-full px-4"): @@ -95,9 +95,7 @@ def _download_json(self) -> None: ) def _download_yaml(self) -> None: - ui.download( - str.encode(yaml.dump(self.json)), filename=self._get_filename("yaml") - ) + ui.download(str.encode(yaml.dump(self.json)), filename=self._get_filename("yaml")) def _get_filename(self, extension: str) -> str: return f"{self.blitz_app_title.replace(' ', '_').replace('.', '_').lower()}.{extension}" @@ -188,9 +186,7 @@ class UserQuestion(GPTChatComponent): AVATAR_COLOR = "#a72bff" def __init__(self, text: str = "") -> None: - super().__init__( - label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR - ) + super().__init__(label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR) def as_gpt_dict(self) -> ChatCompletionMessageParam: return { @@ -213,9 +209,7 @@ class GPTResponse(GPTChatComponent): AVATAR_COLOR = "#74aa9c" def __init__(self, text: str = "", text_is_finished: bool = False) -> None: - super().__init__( - label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR - ) + super().__init__(label=self.LABEL, text=text, icon=self.ICON, avatar_color=self.AVATAR_COLOR) self._text_is_finished = text_is_finished self.text_is_finished = text_is_finished diff --git a/blitz/ui/components/header.py b/blitz/ui/components/header.py index 5fe180d..fef0848 100644 --- a/blitz/ui/components/header.py +++ b/blitz/ui/components/header.py @@ -28,15 +28,9 @@ def __init__( self.blitz_ui = blitz_ui self.dark_mode = ui.dark_mode(value=True) - self.home_link = ( - f"dashboard/projects/{blitz_ui.current_project}" - if blitz_ui.current_project - else "projects" - ) + self.home_link = f"dashboard/projects/{blitz_ui.current_project}" if blitz_ui.current_project else "projects" self.drawer = drawer - ui.add_head_html( - f"" - ) + ui.add_head_html(f"") ui.add_head_html( f"" @@ -51,30 +45,22 @@ def __init__( ) def render(self) -> None: - with ui.header(bordered=True).classes( - "pl-1 pr-8 justify-between content-center h-16 backdrop-blur-sm" - ): + with ui.header(bordered=True).classes("pl-1 pr-8 justify-between content-center h-16 backdrop-blur-sm"): with ui.row().classes("items-center space-x-20 content-center my-auto"): with ui.row().classes("items-center space-x-0 content-center "): if self.drawer is not None: - ui.button(icon="menu", on_click=self.drawer.toggle).props( - "flat" - ) + ui.button(icon="menu", on_click=self.drawer.toggle).props("flat") ui.icon(name="bolt", color=DARK_PINK, size="32px") with ui.link(target=f"/projects/{self.blitz_ui.current_project}"): ui.label("Blitz Dashboard") with ui.row().classes("items-center justify-between content-center"): - with ui.link( - target=f"{self.blitz_ui.localhost_url}/projects" - ).classes("disabled"): + with ui.link(target=f"{self.blitz_ui.localhost_url}/projects").classes("disabled"): ui.tooltip("Multiple App management is coming soon") ui.label("Projects") with ui.link(target="/gpt"): ui.label("GPT Builder") - with ui.link( - target="https://paperz-org.github.io/blitz/", new_tab=True - ): + with ui.link(target="https://paperz-org.github.io/blitz/", new_tab=True): ui.label("Documentation") with ui.row().classes("items-center content-center my-auto"): with ui.element(): @@ -91,12 +77,8 @@ def render(self) -> None: self.dark_mode, "value", value=True ) ui.tooltip("White mode is coming soon") - with ui.link( - target="https://github.com/Paperz-org/blitz", new_tab=True - ).classes(" w-8"): - ui.image( - Path(__file__).parent.parent / "./assets/github_white.png" - ).classes("w-8 ") + with ui.link(target="https://github.com/Paperz-org/blitz", new_tab=True).classes(" w-8"): + ui.image(Path(__file__).parent.parent / "./assets/github_white.png").classes("w-8 ") class MenuLink: @@ -106,11 +88,9 @@ def __init__(self, label: str, link: str, icon: str) -> None: self.icon = icon def render(self) -> None: - with ui.link(target=self.link).classes("w-full"), ui.button( - on_click=self.go_to - ).props("flat align=left").classes( - "px-4 hover:bg-slate-700 rounded-sm w-full" - ) as self.button: + with ui.link(target=self.link).classes("w-full"), ui.button(on_click=self.go_to).props( + "flat align=left" + ).classes("px-4 hover:bg-slate-700 rounded-sm w-full") as self.button: ui.icon(name=self.icon, size="sm").props("flat").classes("pr-4") ui.label(self.label) @@ -133,20 +113,16 @@ def __init__( self.drawer: LeftDrawer | None = None def left_drawer(self) -> None: - with ui.left_drawer( - value=self.drawer_open, fixed=True, bottom_corner=True - ).props("width=200").classes("px-0 bg-[#14151a]") as self.drawer: - MenuLink( - "Dashboard", f"/projects/{self.current_project}", "dashboard" - ).render() + with ui.left_drawer(value=self.drawer_open, fixed=True, bottom_corner=True).props("width=200").classes( + "px-0 bg-[#14151a]" + ) as self.drawer: + MenuLink("Dashboard", f"/projects/{self.current_project}", "dashboard").render() MenuLink( "Admin", f"{self.blitz_ui.localhost_url}/admin/", "table_chart", ).render() - MenuLink( - "Swagger", f"/projects/{self.current_project}/swagger", "api" - ).render() + MenuLink("Swagger", f"/projects/{self.current_project}/swagger", "api").render() MenuLink( "Blitz File", f"/projects/{self.current_project}/blitz-file", diff --git a/blitz/ui/pages/dashboard.py b/blitz/ui/pages/dashboard.py index 3346c89..ceb09e1 100644 --- a/blitz/ui/pages/dashboard.py +++ b/blitz/ui/pages/dashboard.py @@ -8,23 +8,16 @@ class ProjectDetailComponent(BaseComponent): - def render(self) -> None: with ui.row().classes("w-full justify-between items-center"): if self.current_app is None: # TODO handle error raise Exception - ui.label(f"{self.current_app.file.config.name}").classes( - "text-xl font-bold" - ) - ui.label(f"Version: {self.current_app.file.config.version}").classes( - "font-bold text-sm" - ) + ui.label(f"{self.current_app.file.config.name}").classes("text-xl font-bold") + ui.label(f"Version: {self.current_app.file.config.version}").classes("font-bold text-sm") ui.separator() ui.label(f"Project Path: {self.current_app.path}").classes("text-sm") - ui.label(f"Description: {self.current_app.file.config.description}").classes( - "text-sm font-normal" - ) + ui.label(f"Description: {self.current_app.file.config.description}").classes("text-sm font-normal") class DashboardPage(BasePage): @@ -36,22 +29,12 @@ def setup(self) -> None: def render(self) -> None: with ui.element("div").classes("w-full h-full flex flex-row justify-center"): with ui.column().classes("w-2/3 h-full border rounded-lg border-gray-300"): - with ui.expansion("Project", value=True, icon="info").classes( - "w-full text-bold text-2xl " - ): + with ui.expansion("Project", value=True, icon="info").classes("w-full text-bold text-2xl "): ProjectDetailComponent().render() - with ui.expansion("Resources", value=True, icon="help_outline").classes( - "w-full text-bold text-2xl" - ): - ui.table( - columns=self.columns, rows=self.rows, row_key="name" - ).classes("w-full no-shadow") - with ui.expansion( - "Status", value=True, icon="health_and_safety" - ).classes("w-full text-bold text-2xl"): + with ui.expansion("Resources", value=True, icon="help_outline").classes("w-full text-bold text-2xl"): + ui.table(columns=self.columns, rows=self.rows, row_key="name").classes("w-full no-shadow") + with ui.expansion("Status", value=True, icon="health_and_safety").classes("w-full text-bold text-2xl"): # See https://github.com/zauberzeug/nicegui/issues/2174 StatusComponent().render() # type: ignore - with ui.expansion("Logs", value=False, icon="list").classes( - "w-full text-bold text-2xl" - ): + with ui.expansion("Logs", value=False, icon="list").classes("w-full text-bold text-2xl"): LogComponent().render() diff --git a/blitz/ui/pages/diagram.py b/blitz/ui/pages/diagram.py index 0e35172..e094455 100644 --- a/blitz/ui/pages/diagram.py +++ b/blitz/ui/pages/diagram.py @@ -1,5 +1,4 @@ from nicegui import ui -from blitz.ui.components.header import FrameComponent from blitz.ui.pages.base import BasePage @@ -46,9 +45,5 @@ def render(self) -> None: raise Exception ui.mermaid(self.blitz_ui.erd) with ui.footer().classes("w-full justify-start "): - ui.button(icon="zoom_in", on_click=self.zoom_svg).classes( - "borderrounded-sm" - ).props("flat") - ui.button(icon="zoom_out", on_click=self.unzoom_svg).classes( - "border rounded-sm" - ).props("flat") + ui.button(icon="zoom_in", on_click=self.zoom_svg).classes("borderrounded-sm").props("flat") + ui.button(icon="zoom_out", on_click=self.unzoom_svg).classes("border rounded-sm").props("flat") diff --git a/blitz/ui/pages/gpt_builder.py b/blitz/ui/pages/gpt_builder.py index dac5000..6b47265 100644 --- a/blitz/ui/pages/gpt_builder.py +++ b/blitz/ui/pages/gpt_builder.py @@ -1,6 +1,5 @@ from functools import lru_cache -from typing import Annotated, Any, AsyncGenerator, Callable, cast -from fastapi import Depends +from typing import Any, AsyncGenerator, Callable, cast from openai.types.chat import ChatCompletion, ChatCompletionMessageParam from nicegui import ui, app @@ -62,9 +61,7 @@ class GPTClient: - def __init__( - self, api_key: str, model: str = "gpt-3.5-turbo", pre_prompt: str | None = None - ) -> None: + def __init__(self, api_key: str, model: str = "gpt-3.5-turbo", pre_prompt: str | None = None) -> None: self.model = model self._api_key = api_key self.pre_prompt = pre_prompt @@ -74,9 +71,7 @@ def __init__( def _get_client(api_key: str) -> AsyncOpenAI: return AsyncOpenAI(api_key=api_key) - def _add_preprompt( - self, messages: list[ChatCompletionMessageParam] - ) -> list[ChatCompletionMessageParam]: + def _add_preprompt(self, messages: list[ChatCompletionMessageParam]) -> list[ChatCompletionMessageParam]: messages.insert( 0, { @@ -91,9 +86,7 @@ def refresh_client(self, api_key: str) -> None: self._api_key = api_key self.client = self._get_client(api_key=api_key) - async def stream( - self, messages: list[ChatCompletionMessageParam] - ) -> AsyncStream[ChatCompletion]: + async def stream(self, messages: list[ChatCompletionMessageParam]) -> AsyncStream[ChatCompletion]: if self.pre_prompt: messages = self._add_preprompt(messages) if self.client is None: @@ -188,15 +181,11 @@ def render(self) -> None: def footer(self) -> None: with ui.footer().classes("items-center space-y-0 pt-0 justify-center px-5"): with ui.grid(columns=10).classes("w-full items-center gap-5"): - with ui.button(on_click=self.delete_conversation_dialog.open).props( - "flat size=sm" - ).classes("justify-self-start"): - ui.icon("delete_outline", color="grey-8", size="md").props( - "fab-mini" - ) - with ui.button(on_click=self.open_settings).props("flat").classes( - "justify-self-end" + with ui.button(on_click=self.delete_conversation_dialog.open).props("flat size=sm").classes( + "justify-self-start" ): + ui.icon("delete_outline", color="grey-8", size="md").props("fab-mini") + with ui.button(on_click=self.open_settings).props("flat").classes("justify-self-end"): ui.icon("settings", color="grey-6", size="md").props("fab-mini") with ui.row(wrap=False).classes( @@ -209,22 +198,16 @@ def footer(self) -> None: self.ask_button() # type: ignore ui.space().classes("col-span-2") - ui.label( - "ChatGPT can make mistakes. Consider checking important information." - ).classes("text-xs text-gray-500 w-full text-center") + ui.label("ChatGPT can make mistakes. Consider checking important information.").classes( + "text-xs text-gray-500 w-full text-center" + ) def delete_conversation(self) -> None: - with ui.dialog() as self.delete_conversation_dialog, ui.card().classes( - "no-shadow" - ): + with ui.dialog() as self.delete_conversation_dialog, ui.card().classes("no-shadow"): ui.label("Are you sure you want to delete this conversation?") with ui.row().classes("w-full items-center"): - ui.button( - "Cancel", on_click=self.delete_conversation_dialog.close - ).props("flat") - ui.button("Delete", on_click=self._handle_delete_conversation).props( - "flat" - ) + ui.button("Cancel", on_click=self.delete_conversation_dialog.close).props("flat") + ui.button("Delete", on_click=self._handle_delete_conversation).props("flat") def _handle_delete_conversation(self) -> None: self.remove_conversation() @@ -258,9 +241,7 @@ def chat_area(self) -> None: @ui.refreshable def ask_button(self) -> None: ask_button = ( - ui.button(on_click=self.ask_button_trigger) - .props("flat") - .bind_enabled_from(self, "can_send_request") + ui.button(on_click=self.ask_button_trigger).props("flat").bind_enabled_from(self, "can_send_request") ) with ask_button: @@ -287,9 +268,7 @@ async def ask_button_trigger(self) -> None: else: self.gpt_request = "" - app.storage.user["gpt_messages"] = [ - message.to_dict() for message in self.gpt_messages - ] + app.storage.user["gpt_messages"] = [message.to_dict() for message in self.gpt_messages] self.ask_button.refresh() async def _handle_ask_event(self) -> None: @@ -331,9 +310,7 @@ def __init__( blitz_ui: BlitzUI = get_blitz_ui(), ) -> None: self.gpt_client = gpt_client - self.dialog = ui.dialog().props( - "maximized transition-show=slide-up transition-hide=slide-down" - ) + self.dialog = ui.dialog().props("maximized transition-show=slide-up transition-hide=slide-down") self.blitz_ui = blitz_ui self.quit_dialog = ui.dialog(value=False) @@ -369,9 +346,9 @@ def header(self) -> None: with ui.row().classes("w-full items-center justify-center"): ui.button(icon="close", on_click=self.close).props("flat") ui.label("Chat Settings").classes("text-2xl font-bold grow text-center") - ui.button("Save", icon="save", on_click=self.save).classes( - "text-color-black" - ).props("flat").bind_enabled_from(self, "settings_has_changed") + ui.button("Save", icon="save", on_click=self.save).classes("text-color-black").props( + "flat" + ).bind_enabled_from(self, "settings_has_changed") @ui.refreshable def openai_settings(self) -> None: @@ -393,9 +370,7 @@ def openai_settings(self) -> None: @ui.refreshable def pre_prompt_editor(self) -> None: with ui.row().classes("w-full items-center"): - ui.button("Reset Pre-Prompt", on_click=self.reset_preprompt).props( - "outline" - ) + ui.button("Reset Pre-Prompt", on_click=self.reset_preprompt).props("outline") switch = ui.switch("Edit Pre-Prompt", value=False) self.preprompt = ( ui.textarea(label="Pre-Prompt", value=self.blitz_ui.preprompt) diff --git a/blitz/ui/pages/log.py b/blitz/ui/pages/log.py index 167c1f7..f62777b 100644 --- a/blitz/ui/pages/log.py +++ b/blitz/ui/pages/log.py @@ -1,4 +1,3 @@ -from blitz.ui.components.header import FrameComponent from blitz.ui.components.logger import LogComponent from blitz.ui.pages.base import BasePage