From 07cc7f15d507576cf1f3833f104fd6c01c73ce4e Mon Sep 17 00:00:00 2001 From: ThatOneCalculator Date: Wed, 3 Jan 2024 14:33:57 -0800 Subject: [PATCH] chore: :rotating_light: lint and format --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- .github/ISSUE_TEMPLATE/feature_request.md | 1 - backend/apps/ollama/main.py | 24 +++++++------ backend/apps/web/main.py | 5 +-- backend/apps/web/models/auths.py | 25 ++++++++----- backend/apps/web/models/chats.py | 39 ++++++++++---------- backend/apps/web/models/modelfiles.py | 25 ++++++------- backend/apps/web/models/prompts.py | 16 ++++----- backend/apps/web/models/users.py | 19 +++++----- backend/apps/web/routers/auths.py | 22 +++++------- backend/apps/web/routers/chats.py | 30 ++++++++-------- backend/apps/web/routers/configs.py | 7 ++-- backend/apps/web/routers/modelfiles.py | 43 +++++++++++------------ backend/apps/web/routers/prompts.py | 13 +++---- backend/apps/web/routers/users.py | 11 +++--- backend/apps/web/routers/utils.py | 17 ++++----- backend/config.py | 5 ++- backend/constants.py | 4 +-- backend/main.py | 5 ++- backend/utils/utils.py | 17 +++++---- docker-compose.data.yaml | 2 +- docker-compose.yaml | 2 +- src/lib/apis/openai/index.ts | 2 +- src/lib/utils/index.ts | 4 +-- static/manifest.json | 30 ++++++++-------- 25 files changed, 190 insertions(+), 180 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 19027013..5a85d087 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -4,7 +4,6 @@ about: Create a report to help us improve title: '' labels: '' assignees: '' - --- # Bug Report @@ -31,6 +30,7 @@ assignees: '' ## Reproduction Details **Confirmation:** + - [ ] I have read and followed all the instructions provided in the README.md. - [ ] I have reviewed the troubleshooting.md document. - [ ] I have included the browser console logs. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index bbcbbe7d..2f28cead 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -4,7 +4,6 @@ about: Suggest an idea for this project title: '' labels: '' assignees: '' - --- **Is your feature request related to a problem? Please describe.** diff --git a/backend/apps/ollama/main.py b/backend/apps/ollama/main.py index 7e138c39..8101d266 100644 --- a/backend/apps/ollama/main.py +++ b/backend/apps/ollama/main.py @@ -1,11 +1,9 @@ from flask import Flask, request, Response, jsonify from flask_cors import CORS - import requests import json - from apps.web.models.users import Users from constants import ERROR_MESSAGES from utils.utils import decode_token @@ -20,7 +18,9 @@ CORS( TARGET_SERVER_URL = OLLAMA_API_BASE_URL -@app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE"]) +@app.route("/", + defaults={"path": ""}, + methods=["GET", "POST", "PUT", "DELETE"]) @app.route("/", methods=["GET", "POST", "PUT", "DELETE"]) def proxy(path): # Combine the base URL of the target server with the requested path @@ -49,13 +49,17 @@ def proxy(path): pass else: return ( - jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}), + jsonify({ + "detail": + ERROR_MESSAGES.ACCESS_PROHIBITED + }), 401, ) else: pass else: - return jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}), 401 + return jsonify( + {"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}), 401 else: return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401 else: @@ -105,12 +109,10 @@ def proxy(path): print(res) return ( - jsonify( - { - "detail": error_detail, - "message": str(e), - } - ), + jsonify({ + "detail": error_detail, + "message": str(e), + }), 400, ) diff --git a/backend/apps/web/main.py b/backend/apps/web/main.py index 153b5dcb..0030c25e 100644 --- a/backend/apps/web/main.py +++ b/backend/apps/web/main.py @@ -22,10 +22,11 @@ app.add_middleware( app.include_router(auths.router, prefix="/auths", tags=["auths"]) app.include_router(users.router, prefix="/users", tags=["users"]) app.include_router(chats.router, prefix="/chats", tags=["chats"]) -app.include_router(modelfiles.router, prefix="/modelfiles", tags=["modelfiles"]) +app.include_router(modelfiles.router, + prefix="/modelfiles", + tags=["modelfiles"]) app.include_router(prompts.router, prefix="/prompts", tags=["prompts"]) - app.include_router(configs.router, prefix="/configs", tags=["configs"]) app.include_router(utils.router, prefix="/utils", tags=["utils"]) diff --git a/backend/apps/web/models/auths.py b/backend/apps/web/models/auths.py index 800750c3..68b284ea 100644 --- a/backend/apps/web/models/auths.py +++ b/backend/apps/web/models/auths.py @@ -4,7 +4,6 @@ import time import uuid from peewee import * - from apps.web.models.users import UserModel, Users from utils.utils import ( verify_password, @@ -76,20 +75,26 @@ class SignupForm(BaseModel): class AuthsTable: + def __init__(self, db): self.db = db self.db.create_tables([Auth]) - def insert_new_auth( - self, email: str, password: str, name: str, role: str = "pending" - ) -> Optional[UserModel]: + def insert_new_auth(self, + email: str, + password: str, + name: str, + role: str = "pending") -> Optional[UserModel]: print("insert_new_auth") id = str(uuid.uuid4()) - auth = AuthModel( - **{"id": id, "email": email, "password": password, "active": True} - ) + auth = AuthModel(**{ + "id": id, + "email": email, + "password": password, + "active": True + }) result = Auth.create(**auth.model_dump()) user = Users.insert_new_user(id, name, email, role) @@ -99,7 +104,8 @@ class AuthsTable: else: return None - def authenticate_user(self, email: str, password: str) -> Optional[UserModel]: + def authenticate_user(self, email: str, + password: str) -> Optional[UserModel]: print("authenticate_user", email) try: auth = Auth.get(Auth.email == email, Auth.active == True) @@ -131,7 +137,8 @@ class AuthsTable: if result: # Delete Auth query = Auth.delete().where(Auth.id == id) - query.execute() # Remove the rows, return number of rows removed. + query.execute( + ) # Remove the rows, return number of rows removed. return True else: diff --git a/backend/apps/web/models/chats.py b/backend/apps/web/models/chats.py index ebc17d9a..bc4659de 100644 --- a/backend/apps/web/models/chats.py +++ b/backend/apps/web/models/chats.py @@ -3,14 +3,12 @@ from typing import List, Union, Optional from peewee import * from playhouse.shortcuts import model_to_dict - import json import uuid import time from apps.web.internal.db import DB - #################### # Chat DB Schema #################### @@ -62,23 +60,23 @@ class ChatTitleIdResponse(BaseModel): class ChatTable: + def __init__(self, db): self.db = db db.create_tables([Chat]) - def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]: + def insert_new_chat(self, user_id: str, + form_data: ChatForm) -> Optional[ChatModel]: id = str(uuid.uuid4()) chat = ChatModel( **{ "id": id, "user_id": user_id, - "title": form_data.chat["title"] - if "title" in form_data.chat - else "New Chat", + "title": form_data.chat["title"] if "title" in + form_data.chat else "New Chat", "chat": json.dumps(form_data.chat), "timestamp": int(time.time()), - } - ) + }) result = Chat.create(**chat.model_dump()) return chat if result else None @@ -111,27 +109,25 @@ class ChatTable: except: return None - def get_chat_lists_by_user_id( - self, user_id: str, skip: int = 0, limit: int = 50 - ) -> List[ChatModel]: + def get_chat_lists_by_user_id(self, + user_id: str, + skip: int = 0, + limit: int = 50) -> List[ChatModel]: return [ - ChatModel(**model_to_dict(chat)) - for chat in Chat.select() - .where(Chat.user_id == user_id) - .order_by(Chat.timestamp.desc()) + ChatModel(**model_to_dict(chat)) for chat in Chat.select().where( + Chat.user_id == user_id).order_by(Chat.timestamp.desc()) # .limit(limit) # .offset(skip) ] def get_all_chats_by_user_id(self, user_id: str) -> List[ChatModel]: return [ - ChatModel(**model_to_dict(chat)) - for chat in Chat.select() - .where(Chat.user_id == user_id) - .order_by(Chat.timestamp.desc()) + ChatModel(**model_to_dict(chat)) for chat in Chat.select().where( + Chat.user_id == user_id).order_by(Chat.timestamp.desc()) ] - def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]: + def get_chat_by_id_and_user_id(self, id: str, + user_id: str) -> Optional[ChatModel]: try: chat = Chat.get(Chat.id == id, Chat.user_id == user_id) return ChatModel(**model_to_dict(chat)) @@ -146,7 +142,8 @@ class ChatTable: def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool: try: - query = Chat.delete().where((Chat.id == id) & (Chat.user_id == user_id)) + query = Chat.delete().where((Chat.id == id) + & (Chat.user_id == user_id)) query.execute() # Remove the rows, return number of rows removed. return True diff --git a/backend/apps/web/models/modelfiles.py b/backend/apps/web/models/modelfiles.py index 8231d8df..51eccfb5 100644 --- a/backend/apps/web/models/modelfiles.py +++ b/backend/apps/web/models/modelfiles.py @@ -58,13 +58,14 @@ class ModelfileResponse(BaseModel): class ModelfilesTable: + def __init__(self, db): self.db = db self.db.create_tables([Modelfile]) def insert_new_modelfile( - self, user_id: str, form_data: ModelfileForm - ) -> Optional[ModelfileModel]: + self, user_id: str, + form_data: ModelfileForm) -> Optional[ModelfileModel]: if "tagName" in form_data.modelfile: modelfile = ModelfileModel( **{ @@ -72,8 +73,7 @@ class ModelfilesTable: "tag_name": form_data.modelfile["tagName"], "modelfile": json.dumps(form_data.modelfile), "timestamp": int(time.time()), - } - ) + }) try: result = Modelfile.create(**modelfile.model_dump()) @@ -87,28 +87,29 @@ class ModelfilesTable: else: return None - def get_modelfile_by_tag_name(self, tag_name: str) -> Optional[ModelfileModel]: + def get_modelfile_by_tag_name(self, + tag_name: str) -> Optional[ModelfileModel]: try: modelfile = Modelfile.get(Modelfile.tag_name == tag_name) return ModelfileModel(**model_to_dict(modelfile)) except: return None - def get_modelfiles(self, skip: int = 0, limit: int = 50) -> List[ModelfileResponse]: + def get_modelfiles(self, + skip: int = 0, + limit: int = 50) -> List[ModelfileResponse]: return [ ModelfileResponse( **{ **model_to_dict(modelfile), - "modelfile": json.loads(modelfile.modelfile), - } - ) - for modelfile in Modelfile.select() + "modelfile": + json.loads(modelfile.modelfile), + }) for modelfile in Modelfile.select() # .limit(limit).offset(skip) ] def update_modelfile_by_tag_name( - self, tag_name: str, modelfile: dict - ) -> Optional[ModelfileModel]: + self, tag_name: str, modelfile: dict) -> Optional[ModelfileModel]: try: query = Modelfile.update( modelfile=json.dumps(modelfile), diff --git a/backend/apps/web/models/prompts.py b/backend/apps/web/models/prompts.py index bb0710b6..044a3697 100644 --- a/backend/apps/web/models/prompts.py +++ b/backend/apps/web/models/prompts.py @@ -47,13 +47,13 @@ class PromptForm(BaseModel): class PromptsTable: + def __init__(self, db): self.db = db self.db.create_tables([Prompt]) - def insert_new_prompt( - self, user_id: str, form_data: PromptForm - ) -> Optional[PromptModel]: + def insert_new_prompt(self, user_id: str, + form_data: PromptForm) -> Optional[PromptModel]: prompt = PromptModel( **{ "user_id": user_id, @@ -61,8 +61,7 @@ class PromptsTable: "title": form_data.title, "content": form_data.content, "timestamp": int(time.time()), - } - ) + }) try: result = Prompt.create(**prompt.model_dump()) @@ -82,14 +81,13 @@ class PromptsTable: def get_prompts(self) -> List[PromptModel]: return [ - PromptModel(**model_to_dict(prompt)) - for prompt in Prompt.select() + PromptModel(**model_to_dict(prompt)) for prompt in Prompt.select() # .limit(limit).offset(skip) ] def update_prompt_by_command( - self, command: str, form_data: PromptForm - ) -> Optional[PromptModel]: + self, command: str, + form_data: PromptForm) -> Optional[PromptModel]: try: query = Prompt.update( title=form_data.title, diff --git a/backend/apps/web/models/users.py b/backend/apps/web/models/users.py index b1de7c33..dc480882 100644 --- a/backend/apps/web/models/users.py +++ b/backend/apps/web/models/users.py @@ -8,7 +8,6 @@ from utils.misc import get_gravatar_url from apps.web.internal.db import DB from apps.web.models.chats import Chats - #################### # User DB Schema #################### @@ -46,13 +45,16 @@ class UserRoleUpdateForm(BaseModel): class UsersTable: + def __init__(self, db): self.db = db self.db.create_tables([User]) - def insert_new_user( - self, id: str, name: str, email: str, role: str = "pending" - ) -> Optional[UserModel]: + def insert_new_user(self, + id: str, + name: str, + email: str, + role: str = "pending") -> Optional[UserModel]: user = UserModel( **{ "id": id, @@ -61,8 +63,7 @@ class UsersTable: "role": role, "profile_image_url": get_gravatar_url(email), "timestamp": int(time.time()), - } - ) + }) result = User.create(**user.model_dump()) if result: return user @@ -92,7 +93,8 @@ class UsersTable: def get_num_users(self) -> Optional[int]: return User.select().count() - def update_user_role_by_id(self, id: str, role: str) -> Optional[UserModel]: + def update_user_role_by_id(self, id: str, + role: str) -> Optional[UserModel]: try: query = User.update(role=role).where(User.id == id) query.execute() @@ -110,7 +112,8 @@ class UsersTable: if result: # Delete User query = User.delete().where(User.id == id) - query.execute() # Remove the rows, return number of rows removed. + query.execute( + ) # Remove the rows, return number of rows removed. return True else: diff --git a/backend/apps/web/routers/auths.py b/backend/apps/web/routers/auths.py index 714982e3..f245601d 100644 --- a/backend/apps/web/routers/auths.py +++ b/backend/apps/web/routers/auths.py @@ -8,7 +8,6 @@ from pydantic import BaseModel import time import uuid - from apps.web.models.auths import ( SigninForm, SignupForm, @@ -19,12 +18,10 @@ from apps.web.models.auths import ( ) from apps.web.models.users import Users - from utils.utils import get_password_hash, get_current_user, create_token from utils.misc import get_gravatar_url, validate_email_format from constants import ERROR_MESSAGES - router = APIRouter() ############################ @@ -49,9 +46,8 @@ async def get_session_user(user=Depends(get_current_user)): @router.post("/update/password", response_model=bool) -async def update_password( - form_data: UpdatePasswordForm, session_user=Depends(get_current_user) -): +async def update_password(form_data: UpdatePasswordForm, + session_user=Depends(get_current_user)): if session_user: user = Auths.authenticate_user(session_user.email, form_data.password) @@ -101,9 +97,8 @@ async def signup(request: Request, form_data: SignupForm): try: role = "admin" if Users.get_num_users() == 0 else "pending" hashed = get_password_hash(form_data.password) - user = Auths.insert_new_auth( - form_data.email.lower(), hashed, form_data.name, role - ) + user = Auths.insert_new_auth(form_data.email.lower(), + hashed, form_data.name, role) if user: token = create_token(data={"email": user.email}) @@ -120,14 +115,15 @@ async def signup(request: Request, form_data: SignupForm): } else: raise HTTPException( - 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR - ) + 500, detail=ERROR_MESSAGES.CREATE_USER_ERROR) except Exception as err: - raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err)) + raise HTTPException(500, + detail=ERROR_MESSAGES.DEFAULT(err)) else: raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN) else: - raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT) + raise HTTPException(400, + detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT) else: raise HTTPException(400, detail=ERROR_MESSAGES.ACCESS_PROHIBITED) diff --git a/backend/apps/web/routers/chats.py b/backend/apps/web/routers/chats.py index 0eec4553..f061b145 100644 --- a/backend/apps/web/routers/chats.py +++ b/backend/apps/web/routers/chats.py @@ -17,8 +17,7 @@ from apps.web.models.chats import ( ) from utils.utils import ( - bearer_scheme, -) + bearer_scheme, ) from constants import ERROR_MESSAGES router = APIRouter() @@ -30,8 +29,7 @@ router = APIRouter() @router.get("/", response_model=List[ChatTitleIdResponse]) async def get_user_chats( - user=Depends(get_current_user), skip: int = 0, limit: int = 50 -): + user=Depends(get_current_user), skip: int = 0, limit: int = 50): return Chats.get_chat_lists_by_user_id(user.id, skip, limit) @@ -43,8 +41,9 @@ async def get_user_chats( @router.get("/all", response_model=List[ChatResponse]) async def get_all_user_chats(user=Depends(get_current_user)): return [ - ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)}) - for chat in Chats.get_all_chats_by_user_id(user.id) + ChatResponse(**{ + **chat.model_dump(), "chat": json.loads(chat.chat) + }) for chat in Chats.get_all_chats_by_user_id(user.id) ] @@ -69,11 +68,12 @@ async def get_chat_by_id(id: str, user=Depends(get_current_user)): chat = Chats.get_chat_by_id_and_user_id(id, user.id) if chat: - return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)}) + return ChatResponse(**{ + **chat.model_dump(), "chat": json.loads(chat.chat) + }) else: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND - ) + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, + detail=ERROR_MESSAGES.NOT_FOUND) ############################ @@ -82,15 +82,17 @@ async def get_chat_by_id(id: str, user=Depends(get_current_user)): @router.post("/{id}", response_model=Optional[ChatResponse]) -async def update_chat_by_id( - id: str, form_data: ChatForm, user=Depends(get_current_user) -): +async def update_chat_by_id(id: str, + form_data: ChatForm, + user=Depends(get_current_user)): chat = Chats.get_chat_by_id_and_user_id(id, user.id) if chat: updated_chat = {**json.loads(chat.chat), **form_data.chat} chat = Chats.update_chat_by_id(id, updated_chat) - return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)}) + return ChatResponse(**{ + **chat.model_dump(), "chat": json.loads(chat.chat) + }) else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, diff --git a/backend/apps/web/routers/configs.py b/backend/apps/web/routers/configs.py index b57fae3d..4dfe79fd 100644 --- a/backend/apps/web/routers/configs.py +++ b/backend/apps/web/routers/configs.py @@ -10,7 +10,6 @@ import uuid from apps.web.models.users import Users - from utils.utils import get_password_hash, get_current_user, create_token from utils.misc import get_gravatar_url, validate_email_format from constants import ERROR_MESSAGES @@ -28,9 +27,9 @@ class SetDefaultModelsForm(BaseModel): @router.post("/default/models", response_model=str) -async def set_global_default_models( - request: Request, form_data: SetDefaultModelsForm, user=Depends(get_current_user) -): +async def set_global_default_models(request: Request, + form_data: SetDefaultModelsForm, + user=Depends(get_current_user)): if user.role == "admin": request.app.state.DEFAULT_MODELS = form_data.models return request.app.state.DEFAULT_MODELS diff --git a/backend/apps/web/routers/modelfiles.py b/backend/apps/web/routers/modelfiles.py index 841d534d..0af9ca0f 100644 --- a/backend/apps/web/routers/modelfiles.py +++ b/backend/apps/web/routers/modelfiles.py @@ -24,7 +24,9 @@ router = APIRouter() @router.get("/", response_model=List[ModelfileResponse]) -async def get_modelfiles(skip: int = 0, limit: int = 50, user=Depends(get_current_user)): +async def get_modelfiles(skip: int = 0, + limit: int = 50, + user=Depends(get_current_user)): return Modelfiles.get_modelfiles(skip, limit) @@ -34,9 +36,8 @@ async def get_modelfiles(skip: int = 0, limit: int = 50, user=Depends(get_curren @router.post("/create", response_model=Optional[ModelfileResponse]) -async def create_new_modelfile( - form_data: ModelfileForm, user=Depends(get_current_user) -): +async def create_new_modelfile(form_data: ModelfileForm, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -49,9 +50,9 @@ async def create_new_modelfile( return ModelfileResponse( **{ **modelfile.model_dump(), - "modelfile": json.loads(modelfile.modelfile), - } - ) + "modelfile": + json.loads(modelfile.modelfile), + }) else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -65,16 +66,17 @@ async def create_new_modelfile( @router.post("/", response_model=Optional[ModelfileResponse]) -async def get_modelfile_by_tag_name(form_data: ModelfileTagNameForm, user=Depends(get_current_user)): +async def get_modelfile_by_tag_name(form_data: ModelfileTagNameForm, + user=Depends(get_current_user)): modelfile = Modelfiles.get_modelfile_by_tag_name(form_data.tag_name) if modelfile: return ModelfileResponse( **{ **modelfile.model_dump(), - "modelfile": json.loads(modelfile.modelfile), - } - ) + "modelfile": + json.loads(modelfile.modelfile), + }) else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -88,9 +90,8 @@ async def get_modelfile_by_tag_name(form_data: ModelfileTagNameForm, user=Depend @router.post("/update", response_model=Optional[ModelfileResponse]) -async def update_modelfile_by_tag_name( - form_data: ModelfileUpdateForm, user=Depends(get_current_user) -): +async def update_modelfile_by_tag_name(form_data: ModelfileUpdateForm, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -104,15 +105,14 @@ async def update_modelfile_by_tag_name( } modelfile = Modelfiles.update_modelfile_by_tag_name( - form_data.tag_name, updated_modelfile - ) + form_data.tag_name, updated_modelfile) return ModelfileResponse( **{ **modelfile.model_dump(), - "modelfile": json.loads(modelfile.modelfile), - } - ) + "modelfile": + json.loads(modelfile.modelfile), + }) else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -126,9 +126,8 @@ async def update_modelfile_by_tag_name( @router.delete("/delete", response_model=bool) -async def delete_modelfile_by_tag_name( - form_data: ModelfileTagNameForm, user=Depends(get_current_user) -): +async def delete_modelfile_by_tag_name(form_data: ModelfileTagNameForm, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, diff --git a/backend/apps/web/routers/prompts.py b/backend/apps/web/routers/prompts.py index 5a002c94..e812555d 100644 --- a/backend/apps/web/routers/prompts.py +++ b/backend/apps/web/routers/prompts.py @@ -6,7 +6,6 @@ from fastapi import APIRouter from pydantic import BaseModel import json - from apps.web.models.prompts import Prompts, PromptForm, PromptModel from utils.utils import get_current_user @@ -30,7 +29,8 @@ async def get_prompts(user=Depends(get_current_user)): @router.post("/create", response_model=Optional[PromptModel]) -async def create_new_prompt(form_data: PromptForm, user=Depends(get_current_user)): +async def create_new_prompt(form_data: PromptForm, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -79,9 +79,9 @@ async def get_prompt_by_command(command: str, user=Depends(get_current_user)): @router.post("/{command}/update", response_model=Optional[PromptModel]) -async def update_prompt_by_command( - command: str, form_data: PromptForm, user=Depends(get_current_user) -): +async def update_prompt_by_command(command: str, + form_data: PromptForm, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -104,7 +104,8 @@ async def update_prompt_by_command( @router.delete("/{command}/delete", response_model=bool) -async def delete_prompt_by_command(command: str, user=Depends(get_current_user)): +async def delete_prompt_by_command(command: str, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, diff --git a/backend/apps/web/routers/users.py b/backend/apps/web/routers/users.py index b3b55268..3281ac65 100644 --- a/backend/apps/web/routers/users.py +++ b/backend/apps/web/routers/users.py @@ -11,11 +11,9 @@ import uuid from apps.web.models.users import UserModel, UserRoleUpdateForm, Users from apps.web.models.auths import Auths - from utils.utils import get_current_user from constants import ERROR_MESSAGES - router = APIRouter() ############################ @@ -24,7 +22,9 @@ router = APIRouter() @router.get("/", response_model=List[UserModel]) -async def get_users(skip: int = 0, limit: int = 50, user=Depends(get_current_user)): +async def get_users(skip: int = 0, + limit: int = 50, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, @@ -39,9 +39,8 @@ async def get_users(skip: int = 0, limit: int = 50, user=Depends(get_current_use @router.post("/update/role", response_model=Optional[UserModel]) -async def update_user_role( - form_data: UserRoleUpdateForm, user=Depends(get_current_user) -): +async def update_user_role(form_data: UserRoleUpdateForm, + user=Depends(get_current_user)): if user.role != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, diff --git a/backend/apps/web/routers/utils.py b/backend/apps/web/routers/utils.py index e9986bab..588ef5a6 100644 --- a/backend/apps/web/routers/utils.py +++ b/backend/apps/web/routers/utils.py @@ -9,12 +9,10 @@ import os import aiohttp import json - from utils.misc import calculate_sha256 from config import OLLAMA_API_BASE_URL - router = APIRouter() @@ -42,7 +40,10 @@ def parse_huggingface_url(hf_url): return None -async def download_file_stream(url, file_path, file_name, chunk_size=1024 * 1024): +async def download_file_stream(url, + file_path, + file_name, + chunk_size=1024 * 1024): done = False if os.path.exists(file_path): @@ -56,7 +57,8 @@ async def download_file_stream(url, file_path, file_name, chunk_size=1024 * 1024 async with aiohttp.ClientSession(timeout=timeout) as session: async with session.get(url, headers=headers) as response: - total_size = int(response.headers.get("content-length", 0)) + current_size + total_size = int(response.headers.get("content-length", + 0)) + current_size with open(file_path, "ab+") as file: async for data in response.content.iter_chunked(chunk_size): @@ -89,9 +91,7 @@ async def download_file_stream(url, file_path, file_name, chunk_size=1024 * 1024 @router.get("/download") -async def download( - url: str, -): +async def download(url: str, ): # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf" file_name = parse_huggingface_url(url) @@ -161,4 +161,5 @@ async def upload(file: UploadFile = File(...)): res = {"error": str(e)} yield f"data: {json.dumps(res)}\n\n" - return StreamingResponse(file_write_stream(), media_type="text/event-stream") + return StreamingResponse(file_write_stream(), + media_type="text/event-stream") diff --git a/backend/config.py b/backend/config.py index 8e100fe5..c79a5f25 100644 --- a/backend/config.py +++ b/backend/config.py @@ -19,9 +19,8 @@ ENV = os.environ.get("ENV", "dev") # OLLAMA_API_BASE_URL #################################### -OLLAMA_API_BASE_URL = os.environ.get( - "OLLAMA_API_BASE_URL", "http://localhost:11434/api" -) +OLLAMA_API_BASE_URL = os.environ.get("OLLAMA_API_BASE_URL", + "http://localhost:11434/api") if ENV == "prod": if OLLAMA_API_BASE_URL == "/ollama/api": diff --git a/backend/constants.py b/backend/constants.py index 0817445b..1d4867cb 100644 --- a/backend/constants.py +++ b/backend/constants.py @@ -6,6 +6,7 @@ class MESSAGES(str, Enum): class ERROR_MESSAGES(str, Enum): + def __str__(self) -> str: return super().__str__() @@ -29,8 +30,7 @@ class ERROR_MESSAGES(str, Enum): UNAUTHORIZED = "401 Unauthorized" ACCESS_PROHIBITED = "You do not have permission to access this resource. Please contact your administrator for assistance." ACTION_PROHIBITED = ( - "The requested action has been restricted as a security measure." - ) + "The requested action has been restricted as a security measure.") NOT_FOUND = "We could not find what you're looking for :/" USER_NOT_FOUND = "We could not find what you're looking for :/" MALICIOUS = "Unusual activities detected, please try again in a few minutes." diff --git a/backend/main.py b/backend/main.py index 24bad0c9..1f432782 100644 --- a/backend/main.py +++ b/backend/main.py @@ -12,6 +12,7 @@ import time class SPAStaticFiles(StaticFiles): + async def get_response(self, path: str, scope): try: return await super().get_response(path, scope) @@ -47,4 +48,6 @@ async def check_url(request: Request, call_next): app.mount("/api/v1", webui_app) app.mount("/ollama/api", WSGIMiddleware(ollama_app)) -app.mount("/", SPAStaticFiles(directory="../build", html=True), name="spa-static-files") +app.mount("/", + SPAStaticFiles(directory="../build", html=True), + name="spa-static-files") diff --git a/backend/utils/utils.py b/backend/utils/utils.py index f98644f5..ad77e0c7 100644 --- a/backend/utils/utils.py +++ b/backend/utils/utils.py @@ -23,16 +23,16 @@ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def verify_password(plain_password, hashed_password): - return ( - pwd_context.verify(plain_password, hashed_password) if hashed_password else None - ) + return (pwd_context.verify(plain_password, hashed_password) + if hashed_password else None) def get_password_hash(password): return pwd_context.hash(password) -def create_token(data: dict, expires_delta: Union[timedelta, None] = None) -> str: +def create_token(data: dict, + expires_delta: Union[timedelta, None] = None) -> str: payload = data.copy() if expires_delta: @@ -45,17 +45,20 @@ def create_token(data: dict, expires_delta: Union[timedelta, None] = None) -> st def decode_token(token: str) -> Optional[dict]: try: - decoded = jwt.decode(token, JWT_SECRET_KEY, options={"verify_signature": False}) + decoded = jwt.decode(token, + JWT_SECRET_KEY, + options={"verify_signature": False}) return decoded except Exception as e: return None def extract_token_from_auth_header(auth_header: str): - return auth_header[len("Bearer ") :] + return auth_header[len("Bearer "):] -def get_current_user(auth_token: HTTPAuthorizationCredentials = Depends(HTTPBearer())): +def get_current_user(auth_token: HTTPAuthorizationCredentials = Depends( + HTTPBearer())): data = decode_token(auth_token.credentials) if data != None and "email" in data: user = Users.get_user_by_email(data["email"]) diff --git a/docker-compose.data.yaml b/docker-compose.data.yaml index 57d6fc37..a8f9f77b 100644 --- a/docker-compose.data.yaml +++ b/docker-compose.data.yaml @@ -3,4 +3,4 @@ version: '3.8' services: ollama: volumes: - - ${OLLAMA_DATA_DIR-./ollama-data}:/root/.ollama \ No newline at end of file + - ${OLLAMA_DATA_DIR-./ollama-data}:/root/.ollama diff --git a/docker-compose.yaml b/docker-compose.yaml index 47263b0a..7cd1bde0 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -25,7 +25,7 @@ services: ports: - ${OLLAMA_WEBUI_PORT-3000}:8080 environment: - - "OLLAMA_API_BASE_URL=http://ollama:11434/api" + - 'OLLAMA_API_BASE_URL=http://ollama:11434/api' extra_hosts: - host.docker.internal:host-gateway restart: unless-stopped diff --git a/src/lib/apis/openai/index.ts b/src/lib/apis/openai/index.ts index 89776268..292e1ce7 100644 --- a/src/lib/apis/openai/index.ts +++ b/src/lib/apis/openai/index.ts @@ -25,7 +25,7 @@ export const getOpenAIModels = async ( throw error; } - let models = Array.isArray(res) ? res : res?.data ?? null; + const models = Array.isArray(res) ? res : res?.data ?? null; return models .map((model) => ({ name: model.id, external: true })) diff --git a/src/lib/utils/index.ts b/src/lib/utils/index.ts index 344672da..2029604e 100644 --- a/src/lib/utils/index.ts +++ b/src/lib/utils/index.ts @@ -21,7 +21,7 @@ export const splitStream = (splitOn) => { }; export const convertMessagesToHistory = (messages) => { - let history = { + const history = { messages: {}, currentId: null }; @@ -114,7 +114,7 @@ export const checkVersion = (required, current) => { export const findWordIndices = (text) => { const regex = /\[([^\]]+)\]/g; - let matches = []; + const matches = []; let match; while ((match = regex.exec(text)) !== null) { diff --git a/static/manifest.json b/static/manifest.json index e386dc56..6d8665f8 100644 --- a/static/manifest.json +++ b/static/manifest.json @@ -1,16 +1,16 @@ { - "name": "Ollama Web UI", - "short_name": "Ollama", - "start_url": "/", - "display": "standalone", - "background_color": "#343541", - "theme_color": "#343541", - "orientation": "portrait-primary", - "icons": [ - { - "src": "/favicon.png", - "type": "image/png", - "sizes": "844x884" - } - ] -} \ No newline at end of file + "name": "Ollama Web UI", + "short_name": "Ollama", + "start_url": "/", + "display": "standalone", + "background_color": "#343541", + "theme_color": "#343541", + "orientation": "portrait-primary", + "icons": [ + { + "src": "/favicon.png", + "type": "image/png", + "sizes": "844x884" + } + ] +}