diff --git a/.github/workflows/pre-release.yml b/.github/workflows/pre-release.yml index d2d41cc7..46bee8e0 100644 --- a/.github/workflows/pre-release.yml +++ b/.github/workflows/pre-release.yml @@ -44,6 +44,7 @@ jobs: del ./backend-python/rwkv_pip/cpp/librwkv.so (Get-Content -Path ./backend-golang/app.go) -replace "//go:custom_build windows ", "" | Set-Content -Path ./backend-golang/app.go (Get-Content -Path ./backend-golang/utils.go) -replace "//go:custom_build windows ", "" | Set-Content -Path ./backend-golang/utils.go + go install mvdan.cc/garble@v0.10.1 make Rename-Item -Path "build/bin/RWKV-Runner.exe" -NewName "RWKV-Runner_windows_x64.exe" @@ -75,6 +76,7 @@ jobs: rm ./backend-python/rwkv_pip/cpp/librwkv.dylib rm ./backend-python/rwkv_pip/cpp/rwkv.dll rm ./backend-python/rwkv_pip/webgpu/web_rwkv_py.cp310-win_amd64.pyd + go install mvdan.cc/garble@v0.10.1 make mv build/bin/RWKV-Runner build/bin/RWKV-Runner_linux_x64 @@ -103,6 +105,7 @@ jobs: rm ./backend-python/rwkv_pip/cpp/rwkv.dll rm ./backend-python/rwkv_pip/cpp/librwkv.so rm ./backend-python/rwkv_pip/webgpu/web_rwkv_py.cp310-win_amd64.pyd + go install mvdan.cc/garble@v0.10.1 make cp build/darwin/Readme_Install.txt build/bin/Readme_Install.txt cp build/bin/RWKV-Runner.app/Contents/MacOS/RWKV-Runner build/bin/RWKV-Runner_darwin_universal diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7b78b29b..4ce3be51 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,7 +43,7 @@ jobs: ref: master - uses: actions/setup-go@v5 with: - go-version: "1.22.5" + go-version: "1.20.5" - uses: actions/setup-python@v5 id: cp310 with: @@ -51,6 +51,9 @@ jobs: - uses: crazy-max/ghaction-chocolatey@v3 with: args: install upx + - uses: crazy-max/ghaction-chocolatey@v3 + with: + args: install nsis - run: | Start-BitsTransfer https://github.com/josStorer/ai00_rwkv_server/releases/latest/download/webgpu_server_windows_x86_64.exe ./backend-rust/webgpu_server.exe Start-BitsTransfer https://github.com/josStorer/web-rwkv-converter/releases/latest/download/web-rwkv-converter_windows_x86_64.exe ./backend-rust/web-rwkv-converter.exe @@ -69,10 +72,11 @@ jobs: del ./backend-python/rwkv_pip/cpp/librwkv.so (Get-Content -Path ./backend-golang/app.go) -replace "//go:custom_build windows ", "" | Set-Content -Path ./backend-golang/app.go (Get-Content -Path ./backend-golang/utils.go) -replace "//go:custom_build windows ", "" | Set-Content -Path ./backend-golang/utils.go + go install mvdan.cc/garble@v0.10.1 make Rename-Item -Path "build/bin/RWKV-Runner.exe" -NewName "RWKV-Runner_windows_x64.exe" - - run: gh release upload ${{github.ref_name}} build/bin/RWKV-Runner_windows_x64.exe + - run: gh release upload ${{github.ref_name}} build/bin/RWKV-Runner_windows_x64.exe build/bin/RWKV-Runner-amd64-installer.exe linux: runs-on: ubuntu-20.04 @@ -83,7 +87,7 @@ jobs: ref: master - uses: actions/setup-go@v5 with: - go-version: "1.22.5" + go-version: "1.20.5" - run: | wget https://github.com/josStorer/ai00_rwkv_server/releases/latest/download/webgpu_server_linux_x86_64 -O ./backend-rust/webgpu_server wget https://github.com/josStorer/web-rwkv-converter/releases/latest/download/web-rwkv-converter_linux_x86_64 -O ./backend-rust/web-rwkv-converter @@ -98,6 +102,7 @@ jobs: rm ./backend-python/rwkv_pip/cpp/librwkv.dylib rm ./backend-python/rwkv_pip/cpp/rwkv.dll rm ./backend-python/rwkv_pip/webgpu/web_rwkv_py.cp310-win_amd64.pyd + go install mvdan.cc/garble@v0.10.1 make mv build/bin/RWKV-Runner build/bin/RWKV-Runner_linux_x64 @@ -112,7 +117,7 @@ jobs: ref: master - uses: actions/setup-go@v5 with: - go-version: "1.22.5" + go-version: "1.20.5" - run: | wget https://github.com/josStorer/ai00_rwkv_server/releases/latest/download/webgpu_server_darwin_aarch64 -O ./backend-rust/webgpu_server wget https://github.com/josStorer/web-rwkv-converter/releases/latest/download/web-rwkv-converter_darwin_aarch64 -O ./backend-rust/web-rwkv-converter @@ -124,12 +129,14 @@ jobs: rm ./backend-python/rwkv_pip/cpp/rwkv.dll rm ./backend-python/rwkv_pip/cpp/librwkv.so rm ./backend-python/rwkv_pip/webgpu/web_rwkv_py.cp310-win_amd64.pyd + go install mvdan.cc/garble@v0.10.1 make cp build/darwin/Readme_Install.txt build/bin/Readme_Install.txt cp build/bin/RWKV-Runner.app/Contents/MacOS/RWKV-Runner build/bin/RWKV-Runner_darwin_universal cd build/bin && zip -r RWKV-Runner_macos_universal.zip RWKV-Runner.app Readme_Install.txt + cd ../../frontend && zip -r html-webui.zip dist - - run: gh release upload ${{github.ref_name}} build/bin/RWKV-Runner_macos_universal.zip build/bin/RWKV-Runner_darwin_universal + - run: gh release upload ${{github.ref_name}} build/bin/RWKV-Runner_macos_universal.zip frontend/html-webui.zip publish-release: runs-on: ubuntu-22.04 diff --git a/.vscode/settings.json b/.vscode/settings.json index 79849377..9e6e8a7d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,7 +1,14 @@ { - "[python]": { - "editor.defaultFormatter": "ms-python.black-formatter" - }, - "python.formatting.provider": "none", - "editor.formatOnSave": true + "prettier.configPath": "./frontend/prettier.config.js", + "prettier.prettierPath": "./frontend/node_modules/prettier", + "prettier.requireConfig": true, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "[go]": { + "editor.defaultFormatter": "golang.go" + }, + "[python]": { + "editor.defaultFormatter": "ms-python.black-formatter" + }, + "python.formatting.provider": "none", + "editor.formatOnSave": true } \ No newline at end of file diff --git a/CURRENT_CHANGE.md b/CURRENT_CHANGE.md index 6a2d111c..6b963e5e 100644 --- a/CURRENT_CHANGE.md +++ b/CURRENT_CHANGE.md @@ -1,23 +1,31 @@ -## Changes +## v1.8.7 + +- withdrawing the obfuscated tiny package, as it caused some exceptions in the html webui + +## v1.8.6 ### Features -- allow the use of the devtools (Ctrl/Cmd+Shift+F12) -- allow custom user avatar image of presets +- feat(python backend): function call support (#368) Great thanks to @EliwiiKeeya + +![image](https://github.com/user-attachments/assets/d1686c4a-4b35-4482-b7d6-ad206b93f20e) + +- feat(ui): add navigator for web on narrow screen (#376) Great thanks to @HaloWang -### Upgrades + -- bump webgpu(python) (https://github.com/cryscan/web-rwkv-py) -- bump rwkv.cpp (rwkv6 support) (https://github.com/RWKV/rwkv.cpp) +- windows installer support: https://github.com/josStorer/RWKV-Runner/releases/latest/download/RWKV-Runner-amd64-installer.exe +- add penalty_decay to the Completion Page ### Improvements -- improve prompts -- improve error notifications during fine-tuning +- improve WSL installation condition detection -### Fixes +### Chores -- fix: #353, numpy2.0 error when fine-tuning +- downgrade to golang1.20 for compatibility with windows7 (#377) +- update manifest.json (hide old models and add new models) +- html-webui.zip is now added to the release ## Install diff --git a/Makefile b/Makefile index 8aed63c2..35c1d1d8 100644 --- a/Makefile +++ b/Makefile @@ -8,8 +8,7 @@ endif build-windows: @echo ---- build for windows - wails build -ldflags '-s -w -extldflags "-static"' -platform windows/amd64 -devtools - upx -9 --lzma ./build/bin/RWKV-Runner.exe + wails build -ldflags '-s -w -extldflags "-static"' -platform windows/amd64 -devtools -upx -upxflags "-9 --lzma" -nsis build-macos: @echo ---- build for macos @@ -17,8 +16,7 @@ build-macos: build-linux: @echo ---- build for linux - wails build -ldflags '-s -w' -platform linux/amd64 -devtools - upx -9 --lzma ./build/bin/RWKV-Runner + wails build -ldflags '-s -w' -platform linux/amd64 -devtools -upx -upxflags "-9 --lzma" build-web: @echo ---- build for web diff --git a/backend-python/routes/completion.py b/backend-python/routes/completion.py index 3ffad8b5..a9c2f5f1 100644 --- a/backend-python/routes/completion.py +++ b/backend-python/routes/completion.py @@ -1,15 +1,22 @@ import asyncio import json from threading import Lock -from typing import List, Union +from typing import List, Union, Literal from enum import Enum import base64 -import time +import time, re, random, string from fastapi import APIRouter, Request, status, HTTPException +from fastapi.encoders import jsonable_encoder from sse_starlette.sse import EventSourceResponse from pydantic import BaseModel, Field import tiktoken + +from routes.schema import ( + ChatCompletionMessageParam, + ChatCompletionToolParam, + ChatCompletionNamedToolChoiceParam, +) from utils.rwkv import * from utils.log import quick_log import global_var @@ -21,12 +28,7 @@ class Role(Enum): User = "user" Assistant = "assistant" System = "system" - - -class Message(BaseModel): - role: Role - content: str = Field(min_length=0) - raw: bool = Field(False, description="Whether to treat content as raw text") + Tool = "tool" default_stop = [ @@ -40,14 +42,19 @@ class Message(BaseModel): "\n\nA", "\n\nBot", "\n\nAlice", + "\n\nObservation", ] class ChatCompletionBody(ModelConfigBody): - messages: Union[List[Message], None] + messages: Union[List[ChatCompletionMessageParam], None] model: Union[str, None] = "rwkv" stream: bool = False stop: Union[str, List[str], None] = default_stop + tools: Union[List[ChatCompletionToolParam], None] = None + tool_choice: Union[ + Literal["none", "auto", "required"], ChatCompletionNamedToolChoiceParam + ] = "auto" user_name: Union[str, None] = Field( None, description="Internal user name", min_length=1 ) @@ -153,41 +160,44 @@ async def eval_rwkv( response, prompt_tokens, completion_tokens = "", 0, 0 completion_start_time = None - for response, delta, prompt_tokens, completion_tokens in model.generate( - prompt, - stop=stop, - ): - if not completion_start_time: - completion_start_time = time.time() - if await request.is_disconnected(): - break - if stream: - yield json.dumps( - { - "object": ( - "chat.completion.chunk" - if chat_mode - else "text_completion" - ), - # "response": response, - "model": model.name, - "choices": [ - ( - { - "delta": {"content": delta}, - "index": 0, - "finish_reason": None, - } + try: + for response, delta, prompt_tokens, completion_tokens in model.generate( + prompt, + stop=stop, + ): + if not completion_start_time: + completion_start_time = time.time() + if await request.is_disconnected(): + break + if stream: + yield json.dumps( + { + "object": ( + "chat.completion.chunk" if chat_mode - else { - "text": delta, - "index": 0, - "finish_reason": None, - } - ) - ], - } - ) + else "text_completion" + ), + # "response": response, + "model": model.name, + "choices": [ + ( + { + "delta": {"content": delta}, + "index": 0, + "finish_reason": None, + } + if chat_mode + else { + "text": delta, + "index": 0, + "finish_reason": None, + } + ) + ], + } + ) + except: + pass # torch_gc() requests_num = requests_num - 1 completion_end_time = time.time() @@ -236,16 +246,10 @@ async def eval_rwkv( } ) yield "[DONE]" - else: + else: # !stream yield { "object": "chat.completion" if chat_mode else "text_completion", - # "response": response, "model": model.name, - "usage": { - "prompt_tokens": prompt_tokens, - "completion_tokens": completion_tokens, - "total_tokens": prompt_tokens + completion_tokens, - }, "choices": [ ( { @@ -264,6 +268,11 @@ async def eval_rwkv( } ) ], + "usage": { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "total_tokens": prompt_tokens + completion_tokens, + }, } @@ -352,17 +361,30 @@ def chat_template( ) system = "System" if body.system_name is None else body.system_name + tool = "Observation" for message in body.messages: append_message: str = "" - if message.role == Role.User: + if message.role == Role.User.value: append_message = f"{user}{interface} " + message.content - elif message.role == Role.Assistant: - append_message = f"{bot}{interface} " + message.content - elif message.role == Role.System: + elif message.role == Role.Assistant.value: + if message.tool_calls and len(message.tool_calls) > 0: + name = message.tool_calls[0].function.name + arguments = json.loads(message.tool_calls[0].function.arguments) + arguments = ", ".join([f'"{k}"="{v}"' for k, v in arguments.items()]) + append_message = ( + f"{bot}{interface} " + + f"{name}\n```python\ntool_call({arguments})\n```" + ) + elif message.content is None: + continue + else: + append_message = f"{bot}{interface} " + message.content + elif message.role == Role.System.value: append_message = f"{system}{interface} " + message.content + elif message.role == Role.Tool.value: + append_message = f"{tool}{interface} " + message.content completion_text += append_message + "\n\n" completion_text += f"{bot}{interface}" - return completion_text @@ -397,6 +419,370 @@ async def chat_completions(body: ChatCompletionBody, request: Request): # if not body.presystem: # body.stop.append("\n\n") + if ( + body.tool_choice != "none" and body.tools is not None and len(body.tools) > 0 + ) or body.messages[-1].role == Role.Tool.value: + return await chat_with_tools(model, body, request, completion_text) + else: + return await chat(model, body, request, completion_text) + + +tool_call_id_timestamps = {} + + +async def chat_with_tools( + model: TextRWKV, body: ChatCompletionBody, request: Request, completion_text: str +): + system = "System" + interface = model.interface + is_with_tool_call_id = body.messages[-1].role == Role.Tool.value + if is_with_tool_call_id: + tool_call_id = body.messages[-1].tool_call_id + tools_text = tool_call_id_timestamps.get(tool_call_id) + else: + tools = [tool.function for tool in body.tools] + tools_text = json.dumps(jsonable_encoder(tools), indent=2) + tool_call_id = generate_tool_call_id() + tool_call_id_timestamps[tool_call_id] = tools_text + if len(tool_call_id_timestamps) > 1000: + tool_call_id_timestamps.pop(next(iter(tool_call_id_timestamps))) + + # Function Call Prompts + tools_text = f"""\ +{system}{interface} You are a helpful assistant with access to the following functions. Use them if required -{tools_text} +""" + + completion_text = tools_text + "\n" + completion_text + + if is_with_tool_call_id: + return await chat(model, body, request, completion_text) + if body.stream: + response = async_generator_stream_response_tool_call( + model, body, request, completion_text, tool_call_id + ) + return EventSourceResponse(response) + else: + response = await chat(model, body, request, completion_text) + if response is not None: + response = postprocess_response(response, tool_call_id) + return response + + +def generate_tool_call_id(): + return "call_" + "".join(random.sample(string.ascii_letters + string.digits, 24)) + + +async def async_generator_stream_response_tool_call( + model: TextRWKV, + body: ChatCompletionBody, + request: Request, + completion_text: str, + tool_call_id: str, +): + # NOTE: There is none of existing failure analysis. + + # Initialization + gen = eval_rwkv( + model, request, body, completion_text, body.stream, body.stop, True + ) # Get an async generator handle + content: str = "" + flag_is_function_call_confirmed = False + flag_is_common_confirmed = False + convert_equal_to_colon = False + + # Loop, there is only one existing endpoint. + done = False + stack_keyword_pairs = [["```", "```"], ["(", ")"], ['"', '"'], ["'", "'"]] + while True: + if done: + if not flag_is_common_confirmed and not flag_is_function_call_confirmed: + yield json.dumps( + { + "object": "chat.completion.chunk", + "model": model.name, + "choices": [ + { + "index": 0, + "delta": {"content": content}, + "finish_reason": None, + } + ], + } + ) + yield json.dumps( + { + "object": "chat.completion.chunk", + "model": model.name, + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], + } + ) + elif flag_is_function_call_confirmed: + yield json.dumps( + { + "object": "chat.completion.chunk", + "model": model.name, + "choices": [ + {"index": 0, "delta": {}, "finish_reason": "tool_calls"} + ], + } + ) + yield "[DONE]" + break + + try: + response = await gen.__anext__() # Generate a delta response + if response == "[DONE]": + done = True + continue + except StopAsyncIteration: + break + + if flag_is_common_confirmed: + yield response + continue + + # Post process response + response_decoded = json.loads(response) # Decode string + delta = response_decoded["choices"][0]["delta"] + if delta == {}: + continue + delta_content: str = delta["content"] + content += delta_content + + if flag_is_function_call_confirmed: + if "\n\n" in content: + done = True + continue + + for pair in stack_keyword_pairs: + if done: + break + for keyword in pair: + if keyword in delta_content: + stack.append(keyword) + if ( + pair[0] in stack + and pair[1] in stack + and ( + ( + pair[0] != pair[1] + and stack.index(pair[0]) < stack.index(pair[1]) + ) + or (pair[0] == pair[1] and stack.count(pair[0]) >= 2) + ) + ): + stack.remove(pair[0]) + stack.remove(pair[1]) + if pair[0] == '"' or pair[0] == "'": + convert_equal_to_colon = True + if "(" not in stack and ")" not in stack: + done = True + response_decoded["choices"][0]["delta"] = { + "tool_calls": [ + { + "index": 0, + "function": { + "arguments": ( + '"' + if delta_content.strip().startswith( + '"' + ) + else ( + "'" + if delta_content.strip().startswith( + "'" + ) + else "" + ) + ) + + "}", + }, + } + ] + } + yield json.dumps(response_decoded) + break + if done: + continue + + if "=" in delta_content and convert_equal_to_colon: + delta_content = delta_content.replace("=", ":") + convert_equal_to_colon = False + response_decoded["choices"][0]["delta"]["content"] = None + response_decoded["choices"][0]["delta"] = { + "tool_calls": [ + { + "index": 0, + "function": { + "arguments": delta_content, + }, + } + ] + } + yield json.dumps(response_decoded) + continue + + if not flag_is_common_confirmed and not flag_is_function_call_confirmed: + """ + # Unconfirmed Response, check content field by the followings: + # Up to 4 line feeds: Common Response. + # Up to 60 characters: Common Response. + # Up to 44 characters under markdown code block unclosed: Common Response. + # Field "```FunctionName\ntool_call(...)```" detected: Function Call Response. + # - There will be 2 responses generated. + # Default: Unsure Response. + # - Recheck with the next delta.content field added. + """ + # Constant + LIMIT_LINE_FEEDS = 4 + LIMIT_CHARACTERS = 60 + LIMIT_FUNCTION_NAME_CHARACTERS = 44 + REGEX_BLOCKS_HEADERS = r"([\w]+)[\s]*```[\w\s]*tool_call\(" + + # Regex + regex_match_function_call_head: Union[re.Match, None] = re.search( + REGEX_BLOCKS_HEADERS, content + ) + + # Confirm Common Response + if regex_match_function_call_head is None and ( + content.count("\n") >= LIMIT_LINE_FEEDS + or len(content) > LIMIT_CHARACTERS + or ( + len(content) > LIMIT_FUNCTION_NAME_CHARACTERS + and "```" not in content + ) + ): + flag_is_common_confirmed = True + response_decoded["choices"][0]["delta"]["content"] = content + yield json.dumps(response_decoded) + continue + + # Confirm Function call Response + if regex_match_function_call_head is not None: + flag_is_function_call_confirmed = True + stack = ["```", "("] + + # Generate a blank content response + response_decoded["choices"][0]["delta"]["role"] = "assistant" + response_decoded["choices"][0]["delta"]["content"] = None + yield json.dumps(response_decoded) + + # Generate a function call details response + name = regex_match_function_call_head.group(1) + response_decoded["choices"][0]["delta"] = { + "tool_calls": [ + { + "index": 0, + "id": tool_call_id, + "type": "function", + "function": { + "name": name, + "arguments": "", + }, + } + ] + } + yield json.dumps(response_decoded) + response_decoded["choices"][0]["delta"] = { + "tool_calls": [ + { + "index": 0, + "function": { + "arguments": "{" + + ( + '"' + if delta_content.strip().endswith('"') + else ( + "'" + if delta_content.strip().endswith("'") + else "" + ) + ), + }, + } + ] + } + yield json.dumps(response_decoded) + continue + + # Default: Unsure Response + continue + # End of loop body + + +def postprocess_response(response: dict, tool_call_id: str): + # NOTE: There is none of existing failure analysis. + REGEX_BLOCKS = r"([\w]+)[\s]*```[\w\s]*tool_call(.*?)\n*```" + REGEX_ARGS = r'[\'"]([^\'"]+)[\'"]\s*=\s*[\'"]([^\'"]+)[\'"]' + + regex_match = re.search( + REGEX_BLOCKS, response["choices"][0]["message"]["content"], re.DOTALL + ) + if regex_match is None: + return response + + name = regex_match.group(1) + function = regex_match.group(2).strip() + try: + arguments = json.dumps(dict(re.findall(REGEX_ARGS, function))) + except: + return response + + tool_calls = [ + { + "id": tool_call_id, + "type": "function", + "function": { + "name": name, + "arguments": arguments, + }, + } + ] + + response["choices"][0]["message"]["tool_calls"] = tool_calls + response["choices"][0]["message"]["content"] = None + response["choices"][0]["finish_reason"] = "tool_calls" + + return response + + +# ----------------------------------- +# @Description: (reserved) post process multi-function-call responses +# ----------------------------------- +# def postprocess_response(response: dict): +# REGEX_BLOCKS = r'```[\w]*(.*?)```' +# REGEX_FUNCTIONS = r'(\w+)*\(' +# REGEX_ARGS = r'"([^"]+)"\s*=\s*"([^"]+)"' + +# tool_calls = [] +# blocks = re.findall(REGEX_BLOCKS, response["choices"][0]["message"]["content"], re.DOTALL) +# for block in blocks: +# functions = block.strip().split('\n') +# for function in functions: +# name = re.search(REGEX_FUNCTIONS, function).group(1) +# arguments = json.dumps(dict(re.findall(REGEX_ARGS, function))) +# tool_calls.append( +# { +# "id": tool_call_id, +# "type": "function", +# "function": { +# "name": name, +# "arguments": arguments, +# } +# } +# ) + +# response["choices"][0]["message"]["tool_calls"] = tool_calls +# response["choices"][0]["message"]["content"] = None +# response["choices"][0]["finish_reason"] = "tool_calls" + +# return response + + +async def chat( + model: TextRWKV, body: ChatCompletionBody, request: Request, completion_text: str +): if body.stream: return EventSourceResponse( eval_rwkv( diff --git a/backend-python/routes/schema.py b/backend-python/routes/schema.py new file mode 100644 index 00000000..803992ff --- /dev/null +++ b/backend-python/routes/schema.py @@ -0,0 +1,97 @@ +from pydantic import BaseModel, Field +from typing import Literal, Optional, Union, List, Dict + + +class ChatCompletionMessageToolCallParamFunction(BaseModel): + arguments: str = Field( + description=""" + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + ) + name: str = Field(description="The name of the function to call.") + + +class ChatCompletionMessageToolCallParam(BaseModel): + id: str = Field(description="The ID of the tool call.") + function: ChatCompletionMessageToolCallParamFunction = Field( + description="The function that the model called." + ) + type: Literal["function"] + + +class ChatCompletionSystemMessageParam(BaseModel): + content: str + role: Literal["system"] + name: Optional[str] = None + raw: bool = Field(False, description="Whether to treat content as raw text") + + +class ChatCompletionUserMessageParam(BaseModel): + content: str + role: Literal["user"] + name: Optional[str] = None + raw: bool = Field(False, description="Whether to treat content as raw text") + + +class ChatCompletionAssistantMessageParam(BaseModel): + content: Optional[str] = None + role: Literal["assistant"] + name: Optional[str] = None + tool_calls: Optional[List[ChatCompletionMessageToolCallParam]] = Field( + [], description="The tool calls generated by the model, such as function calls." + ) + raw: bool = Field(False, description="Whether to treat content as raw text") + + +class ChatCompletionToolMessageParam(BaseModel): + content: str + role: Literal["tool"] + name: Optional[str] = None + tool_call_id: str = Field( + description="Tool call that this message is responding to." + ) + + +ChatCompletionMessageParam = Union[ + ChatCompletionSystemMessageParam, + ChatCompletionUserMessageParam, + ChatCompletionAssistantMessageParam, + ChatCompletionToolMessageParam, +] + + +class ResponseFormat(BaseModel): + type: Literal["text", "json_object"] + + +class ChatCompletionNamedToolChoiceParamFunction(BaseModel): + name: str + + +class ChatCompletionNamedToolChoiceParam(BaseModel): + function: ChatCompletionNamedToolChoiceParamFunction + type: Literal["function"] = "function" + + +FunctionParameters = Dict[str, object] + + +class FunctionDefinition(BaseModel): + name: str = Field( + min_length=1, + max_length=64, + description="The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.", + ) + description: str = Field( + None, + description="A description of what the function does, used by the model to choose when and how to call the function.", + ) + parameters: Union[FunctionParameters, None] = None + + +class ChatCompletionToolParam(BaseModel): + function: FunctionDefinition + type: Literal["function"] = "function" diff --git a/backend-python/tests/function_call.py b/backend-python/tests/function_call.py new file mode 100644 index 00000000..ed6a0b11 --- /dev/null +++ b/backend-python/tests/function_call.py @@ -0,0 +1,96 @@ +# https://platform.openai.com/docs/guides/function-calling + +from openai import OpenAI +import json + +client = OpenAI( + base_url="http://127.0.0.1:8000", + api_key="test", +) + + +# Example dummy function hard coded to return the same weather +# In production, this could be your backend API or an external API +def get_current_weather(location, unit="fahrenheit"): + """Get the current weather in a given location""" + if "tokyo" in location.lower(): + return json.dumps({"location": "Tokyo", "temperature": "10", "unit": unit}) + elif "san francisco" in location.lower(): + return json.dumps( + {"location": "San Francisco", "temperature": "72", "unit": unit} + ) + elif "paris" in location.lower(): + return json.dumps({"location": "Paris", "temperature": "22", "unit": unit}) + else: + return json.dumps({"location": location, "temperature": "unknown"}) + + +def run_conversation(): + # Step 1: send the conversation and available functions to the model + messages = [ + { + "role": "user", + "content": "What's the weather like in Paris?", + } + ] + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + }, + } + ] + response = client.chat.completions.create( + model="gpt-4o", + messages=messages, + tools=tools, + tool_choice="auto", # auto is default, but we'll be explicit + ) + response_message = response.choices[0].message + tool_calls = response_message.tool_calls + # Step 2: check if the model wanted to call a function + if tool_calls: + # Step 3: call the function + # Note: the JSON response may not always be valid; be sure to handle errors + available_functions = { + "get_current_weather": get_current_weather, + } # only one function in this example, but you can have multiple + messages.append(response_message) # extend conversation with assistant's reply + # Step 4: send the info for each function call and function response to the model + for tool_call in tool_calls: + function_name = tool_call.function.name + function_to_call = available_functions[function_name] + function_args = json.loads(tool_call.function.arguments) + function_response = function_to_call( + location=function_args.get("location"), + unit=function_args.get("unit"), + ) + messages.append( + { + "tool_call_id": tool_call.id, + "role": "tool", + "name": function_name, + "content": function_response, + } + ) # extend conversation with function response + second_response = client.chat.completions.create( + model="gpt-4o", + messages=messages, + ) # get a new response from the model where it can see the function response + return second_response.choices[0].message.content + + +print(run_conversation()) diff --git a/backend-python/tests/function_call_stream.py b/backend-python/tests/function_call_stream.py new file mode 100644 index 00000000..1dcef2fd --- /dev/null +++ b/backend-python/tests/function_call_stream.py @@ -0,0 +1,150 @@ +# Example of an OpenAI ChatCompletion request with stream=True +# https://platform.openai.com/docs/guides/chat +import time +import json +from openai import OpenAI +from collections import defaultdict + +# record the time before the request is sent +start_time = time.time() + + +# Example dummy function hard coded to return the same weather +# In production, this could be your backend API or an external API +def get_current_weather(location, unit="fahrenheit"): + """Get the current weather in a given location""" + if "tokyo" in location.lower(): + return json.dumps({"location": "Tokyo", "temperature": "10", "unit": unit}) + elif "san francisco" in location.lower(): + return json.dumps( + {"location": "San Francisco", "temperature": "72", "unit": unit} + ) + elif "paris" in location.lower(): + return json.dumps({"location": "Paris", "temperature": "22", "unit": unit}) + else: + return json.dumps({"location": location, "temperature": "unknown"}) + + +client = OpenAI( + base_url="http://127.0.0.1:8000", + api_key="test", +) + +messages = [ + { + "role": "user", + "content": "What's the weather like in Paris?", + } +] + +tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + }, + } +] +response = client.chat.completions.create( + model="gpt-4o", + messages=messages, + tools=tools, + tool_choice="auto", # auto is default, but we'll be explicit + stream=True, +) + +# https://community.openai.com/t/has-anyone-managed-to-get-a-tool-call-working-when-stream-true/498867/11 +tool_calls = [] +index = 0 +start = True +for chunk in response: + print(chunk) + chunk_time = time.time() - start_time + + delta = chunk.choices[0].delta + if not delta: + break + if not delta.function_call and not delta.tool_calls: + if start: + continue + else: + break + start = False + if delta.function_call: + if index == len(tool_calls): + tool_calls.append(defaultdict(str)) + if delta.function_call.name: + tool_calls[index]["name"] = delta.function_call.name + if delta.function_call.arguments: + tool_calls[index]["arguments"] += delta.function_call.arguments + elif delta.tool_calls: + tool_call = delta.tool_calls[0] + index = tool_call.index + if index == len(tool_calls): + tool_calls.append(defaultdict(str)) + if tool_call.id: + tool_calls[index]["id"] = tool_call.id + if tool_call.function: + if tool_call.function.name: + tool_calls[index]["name"] = tool_call.function.name + if tool_call.function.arguments: + tool_calls[index]["arguments"] += tool_call.function.arguments + +print() +print(tool_calls) +print(f"Full response received {chunk_time:.2f} seconds after request") + +if tool_calls: + # Step 3: call the function + # Note: the JSON response may not always be valid; be sure to handle errors + available_functions = { + "get_current_weather": get_current_weather, + } # only one function in this example, but you can have multiple + # Step 4: send the info for each function call and function response to the model + for tool_call in tool_calls: + function_name = tool_call["name"] + function_to_call = available_functions[function_name] + function_args = json.loads(tool_call["arguments"]) + function_response = function_to_call( + location=function_args.get("location"), + unit=function_args.get("unit"), + ) + messages.append( + { + "role": "assistant", + "tool_calls": [ + { + "id": tool_call["id"], + "type": "function", + "function": { + "name": function_name, + "arguments": tool_call["arguments"], + }, + } + ], + } + ) # extend conversation with assistant's reply + messages.append( + { + "tool_call_id": tool_call["id"], + "role": "tool", + "content": function_response, + } + ) # extend conversation with function response + second_response = client.chat.completions.create( + model="gpt-4o", + messages=messages, + ) # get a new response from the model where it can see the function response + print(second_response.choices[0].message.content) diff --git a/backend-python/tests/postprocess_response.py b/backend-python/tests/postprocess_response.py new file mode 100644 index 00000000..8f612d3a --- /dev/null +++ b/backend-python/tests/postprocess_response.py @@ -0,0 +1,72 @@ +import re + + +def postprocess_response(s): + REGEX_BLOCKS = r"([\w]+)[\s]*```[\w]*(.*?)```" + REGEX_ARGS = r'"([^"]+)"\s*=\s*"([^"]+)"' + + name = re.search(REGEX_BLOCKS, s, re.DOTALL).group(1) + function = re.search(REGEX_BLOCKS, s, re.DOTALL).group(2).strip() + arguments = dict(re.findall(REGEX_ARGS, function)) + + print(f"Name:\n{name}") + print(f"Function:\n{function}") + print(f"arguments:\n{arguments}") + print() + + return + + +def postprocess_response_reserved(s): + REGEX_BLOCKS = r"```[\w]*(.*?)```" + REGEX_FUNCTIONS = r"(\w+)*\(" + REGEX_ARGS = r'"([^"]+)"\s*=\s*"([^"]+)"' + + blocks = re.findall(REGEX_BLOCKS, s, re.DOTALL) + print(f"Blocks:\n{blocks}") + for block in blocks: + functions = block.strip().split("\n") + print(f"Functions:\n{functions}") + print() + for function in functions: + name = re.search(REGEX_FUNCTIONS, function).group(1) + arguments = f"{dict(re.findall(REGEX_ARGS, function))}" + + print(function) + print(name) + print(arguments) + print() + + return + + +if __name__ == "__main__": + str = """ + some texts + some texts + some texts + some texts + + ```python\n + get_current_wether("location"= "Tokyo", "unit" ="None")\n + ``` + + some texts + some texts + some texts + some texts + """ + postprocess_response(str) + + str = """ get_exchange_rate +```python +tool_call("base_currency"= "func_as_param('Hello World!')", "target_currency"= "CNY") +```""" + postprocess_response(str) + + str = """\ +get_current_weather +```python\n +tool_call("location"= "Tokyo", "unit"= "None")\n +```""" + postprocess_response(str) diff --git a/build/windows/Readme_Install.txt b/build/windows/Readme_Install.txt index 10362e44..e496a052 100644 --- a/build/windows/Readme_Install.txt +++ b/build/windows/Readme_Install.txt @@ -1,6 +1,7 @@ Client Download URL: 客户端下载地址: クライアントのダウンロードURL: +https://github.com/josStorer/RWKV-Runner/releases/latest/download/RWKV-Runner-amd64-installer.exe https://github.com/josStorer/RWKV-Runner/releases/latest/download/RWKV-Runner_windows_x64.exe Please execute this program in an empty directory. All related dependencies will be placed in this directory. diff --git a/build/windows/WELCOMEFINISHPAGE.bmp b/build/windows/WELCOMEFINISHPAGE.bmp new file mode 100644 index 00000000..042ad59f Binary files /dev/null and b/build/windows/WELCOMEFINISHPAGE.bmp differ diff --git a/build/windows/installer/project.nsi b/build/windows/installer/project.nsi index 7b2148bc..ab487481 100644 --- a/build/windows/installer/project.nsi +++ b/build/windows/installer/project.nsi @@ -3,10 +3,10 @@ Unicode true #### ## Please note: Template replacements don't work in this file. They are provided with default defines like ## mentioned underneath. -## If the keyword is not defined, "wails_tools.nsh" will populate them with the values from ProjectInfo. -## If they are defined here, "wails_tools.nsh" will not touch them. This allows to use this project.nsi manually +## If the keyword is not defined, "wails_tools.nsh" will populate them with the values from ProjectInfo. +## If they are defined here, "wails_tools.nsh" will not touch them. This allows to use this project.nsi manually ## from outside of Wails for debugging and development of the installer. -## +## ## For development first make a wails nsis build to populate the "wails_tools.nsh": ## > wails build --target windows/amd64 --nsis ## Then you can call makensis on this file with specifying the path to your binary: @@ -17,7 +17,7 @@ Unicode true ## For a installer with both architectures: ## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app-amd64.exe -DARG_WAILS_ARM64_BINARY=..\..\bin\app-arm64.exe #### -## The following information is taken from the ProjectInfo file, but they can be overwritten here. +## The following information is taken from the ProjectInfo file, but they can be overwritten here. #### ## !define INFO_PROJECTNAME "MyProject" # Default "{{.Name}}" ## !define INFO_COMPANYNAME "MyCompany" # Default "{{.Info.CompanyName}}" @@ -45,6 +45,9 @@ VIAddVersionKey "FileVersion" "${INFO_PRODUCTVERSION}" VIAddVersionKey "LegalCopyright" "${INFO_COPYRIGHT}" VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}" +# Enable HiDPI support. https://nsis.sourceforge.io/Reference/ManifestDPIAware +ManifestDPIAware true + !include "MUI.nsh" !define MUI_ICON "..\icon.ico" @@ -53,36 +56,53 @@ VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}" !define MUI_FINISHPAGE_NOAUTOCLOSE # Wait on the INSTFILES page so the user can take a look into the details of the installation steps !define MUI_ABORTWARNING # This will warn the user if they exit from the installer. +!define MUI_WELCOMEFINISHPAGE_BITMAP_NOSTRETCH +!define MUI_WELCOMEFINISHPAGE_BITMAP "..\WELCOMEFINISHPAGE.bmp" +!define MUI_UNWELCOMEFINISHPAGE_BITMAP_NOSTRETCH +!define MUI_UNWELCOMEFINISHPAGE_BITMAP "..\WELCOMEFINISHPAGE.bmp" + !insertmacro MUI_PAGE_WELCOME # Welcome to the installer page. # !insertmacro MUI_PAGE_LICENSE "resources\eula.txt" # Adds a EULA page to the installer !insertmacro MUI_PAGE_DIRECTORY # In which folder install page. !insertmacro MUI_PAGE_INSTFILES # Installing page. !insertmacro MUI_PAGE_FINISH # Finished installation page. +!insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES # Uinstalling page -!insertmacro MUI_LANGUAGE "English" # Set the Language of the installer - ## The following two statements can be used to sign the installer and the uninstaller. The path to the binaries are provided in %1 #!uninstfinalize 'signtool --file "%1"' #!finalize 'signtool --file "%1"' Name "${INFO_PRODUCTNAME}" OutFile "..\..\bin\${INFO_PROJECTNAME}-${ARCH}-installer.exe" # Name of the installer's file. -InstallDir "$PROGRAMFILES64\${INFO_COMPANYNAME}\${INFO_PRODUCTNAME}" # Default installing folder ($PROGRAMFILES is Program Files folder). +InstallDir "$AppData\${INFO_PRODUCTNAME}" # Default installing folder ($PROGRAMFILES is Program Files folder). ShowInstDetails show # This will always show the installation details. +SetCompress off + +!insertmacro MUI_LANGUAGE "SimpChinese" +!insertmacro MUI_LANGUAGE "TradChinese" +!insertmacro MUI_LANGUAGE "English" +!insertmacro MUI_LANGUAGE "Japanese" +!insertmacro MUI_LANGUAGE "Korean" +!insertmacro MUI_LANGUAGE "Russian" +!insertmacro MUI_RESERVEFILE_LANGDLL + Function .onInit !insertmacro wails.checkArchitecture + !insertmacro MUI_LANGDLL_DISPLAY FunctionEnd Section + ExecWait 'powershell -ExecutionPolicy Bypass -Command "Add-MpPreference -ExclusionPath $\'$INSTDIR$\'"' + !insertmacro wails.setShellContext !insertmacro wails.webview2runtime SetOutPath $INSTDIR - + !insertmacro wails.files CreateShortcut "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}" @@ -91,7 +111,7 @@ Section !insertmacro wails.writeUninstaller SectionEnd -Section "uninstall" +Section "uninstall" !insertmacro wails.setShellContext RMDir /r "$AppData\${PRODUCT_EXECUTABLE}" # Remove the WebView2 DataPath diff --git a/build/windows/installer/wails_tools.nsh b/build/windows/installer/wails_tools.nsh index 467c349a..6979273c 100644 --- a/build/windows/installer/wails_tools.nsh +++ b/build/windows/installer/wails_tools.nsh @@ -5,19 +5,19 @@ !include "FileFunc.nsh" !ifndef INFO_PROJECTNAME - !define INFO_PROJECTNAME "{{.Name}}" + !define INFO_PROJECTNAME "RWKV-Runner" !endif !ifndef INFO_COMPANYNAME - !define INFO_COMPANYNAME "{{.Info.CompanyName}}" + !define INFO_COMPANYNAME "RWKV-Runner" !endif !ifndef INFO_PRODUCTNAME - !define INFO_PRODUCTNAME "{{.Info.ProductName}}" + !define INFO_PRODUCTNAME "RWKV-Runner" !endif !ifndef INFO_PRODUCTVERSION - !define INFO_PRODUCTVERSION "{{.Info.ProductVersion}}" + !define INFO_PRODUCTVERSION "1.0.0" !endif !ifndef INFO_COPYRIGHT - !define INFO_COPYRIGHT "{{.Info.Copyright}}" + !define INFO_COPYRIGHT "Copyright © 2023 RWKV-Runner" !endif !ifndef PRODUCT_EXECUTABLE !define PRODUCT_EXECUTABLE "${INFO_PROJECTNAME}.exe" @@ -163,17 +163,74 @@ RequestExecutionLevel "${REQUEST_EXECUTION_LEVEL}" Goto ok ${EndIf} ${EndIf} - + SetDetailsPrint both DetailPrint "${WAILS_INSTALL_WEBVIEW_DETAILPRINT}" SetDetailsPrint listonly - + InitPluginsDir CreateDirectory "$pluginsdir\webview2bootstrapper" SetOutPath "$pluginsdir\webview2bootstrapper" File "tmp\MicrosoftEdgeWebview2Setup.exe" ExecWait '"$pluginsdir\webview2bootstrapper\MicrosoftEdgeWebview2Setup.exe" /silent /install' - + SetDetailsPrint both ok: -!macroend \ No newline at end of file +!macroend + +# Copy of APP_ASSOCIATE and APP_UNASSOCIATE macros from here https://gist.github.com/nikku/281d0ef126dbc215dd58bfd5b3a5cd5b +!macro APP_ASSOCIATE EXT FILECLASS DESCRIPTION ICON COMMANDTEXT COMMAND + ; Backup the previously associated file class + ReadRegStr $R0 SHELL_CONTEXT "Software\Classes\.${EXT}" "" + WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "${FILECLASS}_backup" "$R0" + + WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "" "${FILECLASS}" + + WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}" "" `${DESCRIPTION}` + WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\DefaultIcon" "" `${ICON}` + WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell" "" "open" + WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell\open" "" `${COMMANDTEXT}` + WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell\open\command" "" `${COMMAND}` +!macroend + +!macro APP_UNASSOCIATE EXT FILECLASS + ; Backup the previously associated file class + ReadRegStr $R0 SHELL_CONTEXT "Software\Classes\.${EXT}" `${FILECLASS}_backup` + WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "" "$R0" + + DeleteRegKey SHELL_CONTEXT `Software\Classes\${FILECLASS}` +!macroend + +!macro wails.associateFiles + ; Create file associations + +!macroend + +!macro wails.unassociateFiles + ; Delete app associations + +!macroend + +!macro CUSTOM_PROTOCOL_ASSOCIATE PROTOCOL DESCRIPTION ICON COMMAND + DeleteRegKey SHELL_CONTEXT "Software\Classes\${PROTOCOL}" + WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}" "" "${DESCRIPTION}" + WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}" "URL Protocol" "" + WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\DefaultIcon" "" "${ICON}" + WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell" "" "" + WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell\open" "" "" + WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell\open\command" "" "${COMMAND}" +!macroend + +!macro CUSTOM_PROTOCOL_UNASSOCIATE PROTOCOL + DeleteRegKey SHELL_CONTEXT "Software\Classes\${PROTOCOL}" +!macroend + +!macro wails.associateCustomProtocols + ; Create custom protocols associations + +!macroend + +!macro wails.unassociateCustomProtocols + ; Delete app custom protocol associations + +!macroend diff --git a/exportModelsJson.js b/exportModelsJson.js index bbcdf315..0e25356b 100644 --- a/exportModelsJson.js +++ b/exportModelsJson.js @@ -31,3 +31,7 @@ document.querySelectorAll('.grid.h-10.grid-cols-12.place-content-center.gap-x-3. modelsJson.push(data) }) + +setTimeout(() => { + console.log(JSON.stringify(modelsJson, null, 2)) +}, 500) diff --git a/frontend/i18nally.json b/frontend/i18nally.json index 6d6a83fb..be6bac3b 100644 --- a/frontend/i18nally.json +++ b/frontend/i18nally.json @@ -81,9 +81,7 @@ } ], "ignores": { - "valuesInProject": [ - "use strict" - ], + "valuesInProject": ["use strict"], "valuesInFile": {}, "filesInProject": [], "unignoredFunctionNames": [], @@ -107,4 +105,4 @@ "middleware" ] } -} \ No newline at end of file +} diff --git a/frontend/package-lock.json b/frontend/package-lock.json index fbf6dbbf..3a04f077 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -44,6 +44,7 @@ "uuid": "^9.0.0" }, "devDependencies": { + "@ianvs/prettier-plugin-sort-imports": "^4.3.1", "@tailwindcss/typography": "^0.5.10", "@types/file-saver": "^2.0.7", "@types/lodash-es": "^4.17.12", @@ -54,6 +55,8 @@ "@vitejs/plugin-react": "^4.0.0", "autoprefixer": "^10.4.14", "postcss": "^8.4.23", + "prettier": "^3.3.3", + "prettier-plugin-tailwindcss": "^0.6.6", "rollup-plugin-visualizer": "^5.9.0", "sass": "^1.62.1", "tailwindcss": "^3.3.2", @@ -85,48 +88,48 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.22.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", - "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", + "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", "dev": true, "dependencies": { - "@babel/highlight": "^7.22.13", - "chalk": "^2.4.2" + "@babel/highlight": "^7.24.7", + "picocolors": "^1.0.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/compat-data": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.22.5.tgz", - "integrity": "sha512-4Jc/YuIaYqKnDDz892kPIledykKg12Aw1PYX5i/TY28anJtacvM1Rrr8wbieB9GfEJwlzqT0hUEao0CxEebiDA==", + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.25.2.tgz", + "integrity": "sha512-bYcppcpKBvX4znYaPEeFau03bp89ShqNMLs+rmdptMw+heSZh9+z84d2YG+K7cYLbWwzdjtDoW/uqZmPjulClQ==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.22.5.tgz", - "integrity": "sha512-SBuTAjg91A3eKOvD+bPEz3LlhHZRNu1nFOVts9lzDJTXshHTjII0BAtDS3Y2DAkdZdDKWVZGVwkDfc4Clxn1dg==", + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.25.2.tgz", + "integrity": "sha512-BBt3opiCOxUr9euZ5/ro/Xv8/V7yJ5bjYMqG/C1YAo8MIKAnumZalCN+msbci3Pigy4lIQfPUpfMM27HMGaYEA==", "dev": true, "dependencies": { "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.22.5", - "@babel/generator": "^7.22.5", - "@babel/helper-compilation-targets": "^7.22.5", - "@babel/helper-module-transforms": "^7.22.5", - "@babel/helpers": "^7.22.5", - "@babel/parser": "^7.22.5", - "@babel/template": "^7.22.5", - "@babel/traverse": "^7.22.5", - "@babel/types": "^7.22.5", - "convert-source-map": "^1.7.0", + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.0", + "@babel/helper-compilation-targets": "^7.25.2", + "@babel/helper-module-transforms": "^7.25.2", + "@babel/helpers": "^7.25.0", + "@babel/parser": "^7.25.0", + "@babel/template": "^7.25.0", + "@babel/traverse": "^7.25.2", + "@babel/types": "^7.25.2", + "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", - "json5": "^2.2.2", - "semver": "^6.3.0" + "json5": "^2.2.3", + "semver": "^6.3.1" }, "engines": { "node": ">=6.9.0" @@ -137,14 +140,14 @@ } }, "node_modules/@babel/generator": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.0.tgz", - "integrity": "sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g==", + "version": "7.25.0", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.25.0.tgz", + "integrity": "sha512-3LEEcj3PVW8pW2R1SR1M89g/qrYk/m/mB/tLqn7dn4sbBUQyTqnlod+II2U4dqiGtUmkcnAmkMDralTFZttRiw==", "dev": true, "dependencies": { - "@babel/types": "^7.23.0", - "@jridgewell/gen-mapping": "^0.3.2", - "@jridgewell/trace-mapping": "^0.3.17", + "@babel/types": "^7.25.0", + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25", "jsesc": "^2.5.1" }, "engines": { @@ -152,87 +155,50 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.22.5.tgz", - "integrity": "sha512-Ji+ywpHeuqxB8WDxraCiqR0xfhYjiDE/e6k7FuIaANnoOFxAHskHChz4vA1mJC9Lbm01s1PVAGhQY4FUKSkGZw==", + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.25.2.tgz", + "integrity": "sha512-U2U5LsSaZ7TAt3cfaymQ8WHh0pxvdHoEk6HVpaexxixjyEquMh0L0YNJNM6CTGKMXV1iksi0iZkGw4AcFkPaaw==", "dev": true, "dependencies": { - "@babel/compat-data": "^7.22.5", - "@babel/helper-validator-option": "^7.22.5", - "browserslist": "^4.21.3", + "@babel/compat-data": "^7.25.2", + "@babel/helper-validator-option": "^7.24.8", + "browserslist": "^4.23.1", "lru-cache": "^5.1.1", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-environment-visitor": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", - "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-function-name": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", - "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", - "dev": true, - "dependencies": { - "@babel/template": "^7.22.15", - "@babel/types": "^7.23.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", - "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" + "semver": "^6.3.1" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-imports": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.5.tgz", - "integrity": "sha512-8Dl6+HD/cKifutF5qGd/8ZJi84QeAKh+CEe1sBzz8UayBBGg1dAIJrdHOcOM5b2MpzWL2yuotJTtGjETq0qjXg==", + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.24.7.tgz", + "integrity": "sha512-8AyH3C+74cgCVVXow/myrynrAGv+nTVg5vKu2nZph9x7RcRwzmh0VFallJuFTZ9mx6u4eSdXZfcOzSqTUm0HCA==", "dev": true, "dependencies": { - "@babel/types": "^7.22.5" + "@babel/traverse": "^7.24.7", + "@babel/types": "^7.24.7" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.22.5.tgz", - "integrity": "sha512-+hGKDt/Ze8GFExiVHno/2dvG5IdstpzCq0y4Qc9OJ25D4q3pKfiIP/4Vp3/JvhDkLKsDK2api3q3fpIgiIF5bw==", + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.25.2.tgz", + "integrity": "sha512-BjyRAbix6j/wv83ftcVJmBt72QtHI56C7JXZoG2xATiLpmoC7dpd8WnkikExHDVPpi/3qCmO6WY1EaXOluiecQ==", "dev": true, "dependencies": { - "@babel/helper-environment-visitor": "^7.22.5", - "@babel/helper-module-imports": "^7.22.5", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.5", - "@babel/template": "^7.22.5", - "@babel/traverse": "^7.22.5", - "@babel/types": "^7.22.5" + "@babel/helper-module-imports": "^7.24.7", + "@babel/helper-simple-access": "^7.24.7", + "@babel/helper-validator-identifier": "^7.24.7", + "@babel/traverse": "^7.25.2" }, "engines": { "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" } }, "node_modules/@babel/helper-plugin-utils": { @@ -245,89 +211,81 @@ } }, "node_modules/@babel/helper-simple-access": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", - "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.22.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", - "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.24.7.tgz", + "integrity": "sha512-zBAIvbCMh5Ts+b86r/CjU+4XGYIs+R1j951gxI3KmmxBMhCg4oQMsv6ZXQ64XOm/cvzfU1FmoCyt6+owc5QMYg==", "dev": true, "dependencies": { - "@babel/types": "^7.22.5" + "@babel/traverse": "^7.24.7", + "@babel/types": "^7.24.7" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-string-parser": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", - "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.8.tgz", + "integrity": "sha512-pO9KhhRcuUyGnJWwyEgnRJTSIZHiT+vMD0kPeD+so0l7mxkMT19g3pjY9GTnHySck/hDzq+dtW/4VgnMkippsQ==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", + "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-option": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.22.5.tgz", - "integrity": "sha512-R3oB6xlIVKUnxNUxbmgq7pKjxpru24zlimpE8WK47fACIlM0II/Hm1RS8IaOI7NgCr6LNS+jl5l75m20npAziw==", + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.24.8.tgz", + "integrity": "sha512-xb8t9tD1MHLungh/AIoWYN+gVHaB9kwlu8gffXGSt3FFEIT7RjS+xWbc2vUD1UTZdIpKj/ab3rdqJ7ufngyi2Q==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helpers": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.22.5.tgz", - "integrity": "sha512-pSXRmfE1vzcUIDFQcSGA5Mr+GxBV9oiRKDuDxXvWQQBCh8HoIjs/2DlDB7H8smac1IVrB9/xdXj2N3Wol9Cr+Q==", + "version": "7.25.0", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.25.0.tgz", + "integrity": "sha512-MjgLZ42aCm0oGjJj8CtSM3DB8NOOf8h2l7DCTePJs29u+v7yO/RBX9nShlKMgFnRks/Q4tBAe7Hxnov9VkGwLw==", "dev": true, "dependencies": { - "@babel/template": "^7.22.5", - "@babel/traverse": "^7.22.5", - "@babel/types": "^7.22.5" + "@babel/template": "^7.25.0", + "@babel/types": "^7.25.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/highlight": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", - "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", + "version": "7.24.7", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", + "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", "dev": true, "dependencies": { - "@babel/helper-validator-identifier": "^7.22.20", + "@babel/helper-validator-identifier": "^7.24.7", "chalk": "^2.4.2", - "js-tokens": "^4.0.0" + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.0.tgz", - "integrity": "sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw==", + "version": "7.25.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.3.tgz", + "integrity": "sha512-iLTJKDbJ4hMvFPgQwwsVoxtHyWpKKPBrxkANrSYewDPaPpT5py5yeVkgPIJ7XYXhndxJpaA3PyALSXQ7u8e/Dw==", "dev": true, + "dependencies": { + "@babel/types": "^7.25.2" + }, "bin": { "parser": "bin/babel-parser.js" }, @@ -377,34 +335,31 @@ } }, "node_modules/@babel/template": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", - "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", + "version": "7.25.0", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.0.tgz", + "integrity": "sha512-aOOgh1/5XzKvg1jvVz7AVrx2piJ2XBi227DHmbY6y+bM9H2FlN+IfecYu4Xl0cNiiVejlsCri89LUsbj8vJD9Q==", "dev": true, "dependencies": { - "@babel/code-frame": "^7.22.13", - "@babel/parser": "^7.22.15", - "@babel/types": "^7.22.15" + "@babel/code-frame": "^7.24.7", + "@babel/parser": "^7.25.0", + "@babel/types": "^7.25.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.23.2", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.2.tgz", - "integrity": "sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.22.13", - "@babel/generator": "^7.23.0", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.23.0", - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.23.0", - "@babel/types": "^7.23.0", - "debug": "^4.1.0", + "version": "7.25.3", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.3.tgz", + "integrity": "sha512-HefgyP1x754oGCsKmV5reSmtV7IXj/kpaE1XYY+D9G5PvKKoFfSbiS4M77MdjuwlZKDIKFCffq9rPU+H/s3ZdQ==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.24.7", + "@babel/generator": "^7.25.0", + "@babel/parser": "^7.25.3", + "@babel/template": "^7.25.0", + "@babel/types": "^7.25.2", + "debug": "^4.3.1", "globals": "^11.1.0" }, "engines": { @@ -412,13 +367,13 @@ } }, "node_modules/@babel/types": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.0.tgz", - "integrity": "sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg==", + "version": "7.25.2", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.2.tgz", + "integrity": "sha512-YTnYtra7W9e6/oAZEHj0bJehPRUlLH9/fbpT5LfB0NhQXyALCRkRs3zH9v07IYhkgpqX6Z78FnuccZr/l4Fs4Q==", "dev": true, "dependencies": { - "@babel/helper-string-parser": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.20", + "@babel/helper-string-parser": "^7.24.8", + "@babel/helper-validator-identifier": "^7.24.7", "to-fast-properties": "^2.0.0" }, "engines": { @@ -2086,15 +2041,50 @@ "csstype": "^3.1.3" } }, + "node_modules/@ianvs/prettier-plugin-sort-imports": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@ianvs/prettier-plugin-sort-imports/-/prettier-plugin-sort-imports-4.3.1.tgz", + "integrity": "sha512-ZHwbyjkANZOjaBm3ZosADD2OUYGFzQGxfy67HmGZU94mHqe7g1LCMA7YYKB1Cq+UTPCBqlAYapY0KXAjKEw8Sg==", + "dev": true, + "dependencies": { + "@babel/core": "^7.24.0", + "@babel/generator": "^7.23.6", + "@babel/parser": "^7.24.0", + "@babel/traverse": "^7.24.0", + "@babel/types": "^7.24.0", + "semver": "^7.5.2" + }, + "peerDependencies": { + "@vue/compiler-sfc": "2.7.x || 3.x", + "prettier": "2 || 3" + }, + "peerDependenciesMeta": { + "@vue/compiler-sfc": { + "optional": true + } + } + }, + "node_modules/@ianvs/prettier-plugin-sort-imports/node_modules/semver": { + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.3", - "resolved": "https://registry.npmmirror.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", - "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", "dev": true, "dependencies": { - "@jridgewell/set-array": "^1.0.1", + "@jridgewell/set-array": "^1.2.1", "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.9" + "@jridgewell/trace-mapping": "^0.3.24" }, "engines": { "node": ">=6.0.0" @@ -2110,9 +2100,9 @@ } }, "node_modules/@jridgewell/set-array": { - "version": "1.1.2", - "resolved": "https://registry.npmmirror.com/@jridgewell/set-array/-/set-array-1.1.2.tgz", - "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", "dev": true, "engines": { "node": ">=6.0.0" @@ -2125,21 +2115,15 @@ "dev": true }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.18", - "resolved": "https://registry.npmmirror.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.18.tgz", - "integrity": "sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==", + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", + "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", "dev": true, "dependencies": { - "@jridgewell/resolve-uri": "3.1.0", - "@jridgewell/sourcemap-codec": "1.4.14" + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@jridgewell/trace-mapping/node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.14", - "resolved": "https://registry.npmmirror.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", - "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==", - "dev": true - }, "node_modules/@kurkle/color": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.2.tgz", @@ -3211,15 +3195,29 @@ } }, "node_modules/browserslist": { - "version": "4.21.5", - "resolved": "https://registry.npmmirror.com/browserslist/-/browserslist-4.21.5.tgz", - "integrity": "sha512-tUkiguQGW7S3IhB7N+c2MV/HZPSCPAAiYBZXLsBhFB/PCy6ZKKsZrmBayHV9fdGV/ARIfJ14NkxKzRDjvp7L6w==", + "version": "4.23.3", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.3.tgz", + "integrity": "sha512-btwCFJVjI4YWDNfau8RhZ+B1Q/VLoUITrm3RlP6y1tYGWIOa+InuYiRGXUBXo8nA1qKmHMyLB/iVQg5TT4eFoA==", "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], "dependencies": { - "caniuse-lite": "^1.0.30001449", - "electron-to-chromium": "^1.4.284", - "node-releases": "^2.0.8", - "update-browserslist-db": "^1.0.10" + "caniuse-lite": "^1.0.30001646", + "electron-to-chromium": "^1.5.4", + "node-releases": "^2.0.18", + "update-browserslist-db": "^1.1.0" }, "bin": { "browserslist": "cli.js" @@ -3251,9 +3249,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001561", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001561.tgz", - "integrity": "sha512-NTt0DNoKe958Q0BE0j0c1V9jbUzhBxHIEJy7asmGrpE0yG63KTV7PLHPnK2E1O9RsQrQ081I3NLuXGS6zht3cw==", + "version": "1.0.30001651", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001651.tgz", + "integrity": "sha512-9Cf+Xv1jJNe1xPZLGuUXLNkE1BoDkqRqYyFJ9TDYSqhduqA4hu4oR9HluGoWYQC/aj8WHjsGVV+bwkh0+tegRg==", "dev": true, "funding": [ { @@ -3504,9 +3502,9 @@ "optional": true }, "node_modules/convert-source-map": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", - "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "dev": true }, "node_modules/core-js": { @@ -3720,9 +3718,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.4.380", - "resolved": "https://registry.npmmirror.com/electron-to-chromium/-/electron-to-chromium-1.4.380.tgz", - "integrity": "sha512-XKGdI4pWM78eLH2cbXJHiBnWUwFSzZM7XujsB6stDiGu9AeSqziedP6amNLpJzE3i0rLTcfAwdCTs5ecP5yeSg==", + "version": "1.5.11", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.11.tgz", + "integrity": "sha512-R1CccCDYqndR25CaXFd6hp/u9RaaMcftMkphmvuepXr5b1vfLkRml6aWVeBhXJ7rbevHkKEMJtz8XqPf7ffmew==", "dev": true }, "node_modules/emoji-regex": { @@ -3779,9 +3777,9 @@ } }, "node_modules/escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmmirror.com/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", + "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", "engines": { "node": ">=6" } @@ -5458,9 +5456,9 @@ } }, "node_modules/node-releases": { - "version": "2.0.10", - "resolved": "https://registry.npmmirror.com/node-releases/-/node-releases-2.0.10.tgz", - "integrity": "sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w==", + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", + "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==", "dev": true }, "node_modules/nopt": { @@ -5600,9 +5598,9 @@ } }, "node_modules/picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", + "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", "dev": true }, "node_modules/picomatch": { @@ -5726,6 +5724,99 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "dev": true }, + "node_modules/prettier": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz", + "integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-plugin-tailwindcss": { + "version": "0.6.6", + "resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.6.tgz", + "integrity": "sha512-OPva5S7WAsPLEsOuOWXATi13QrCKACCiIonFgIR6V4lYv4QLp++UXVhZSzRbZxXGimkQtQT86CC6fQqTOybGng==", + "dev": true, + "engines": { + "node": ">=14.21.3" + }, + "peerDependencies": { + "@ianvs/prettier-plugin-sort-imports": "*", + "@prettier/plugin-pug": "*", + "@shopify/prettier-plugin-liquid": "*", + "@trivago/prettier-plugin-sort-imports": "*", + "@zackad/prettier-plugin-twig-melody": "*", + "prettier": "^3.0", + "prettier-plugin-astro": "*", + "prettier-plugin-css-order": "*", + "prettier-plugin-import-sort": "*", + "prettier-plugin-jsdoc": "*", + "prettier-plugin-marko": "*", + "prettier-plugin-multiline-arrays": "*", + "prettier-plugin-organize-attributes": "*", + "prettier-plugin-organize-imports": "*", + "prettier-plugin-sort-imports": "*", + "prettier-plugin-style-order": "*", + "prettier-plugin-svelte": "*" + }, + "peerDependenciesMeta": { + "@ianvs/prettier-plugin-sort-imports": { + "optional": true + }, + "@prettier/plugin-pug": { + "optional": true + }, + "@shopify/prettier-plugin-liquid": { + "optional": true + }, + "@trivago/prettier-plugin-sort-imports": { + "optional": true + }, + "@zackad/prettier-plugin-twig-melody": { + "optional": true + }, + "prettier-plugin-astro": { + "optional": true + }, + "prettier-plugin-css-order": { + "optional": true + }, + "prettier-plugin-import-sort": { + "optional": true + }, + "prettier-plugin-jsdoc": { + "optional": true + }, + "prettier-plugin-marko": { + "optional": true + }, + "prettier-plugin-multiline-arrays": { + "optional": true + }, + "prettier-plugin-organize-attributes": { + "optional": true + }, + "prettier-plugin-organize-imports": { + "optional": true + }, + "prettier-plugin-sort-imports": { + "optional": true + }, + "prettier-plugin-style-order": { + "optional": true + }, + "prettier-plugin-svelte": { + "optional": true + } + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", @@ -7032,13 +7123,27 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.0.11", - "resolved": "https://registry.npmmirror.com/update-browserslist-db/-/update-browserslist-db-1.0.11.tgz", - "integrity": "sha512-dCwEFf0/oT85M1fHBg4F0jtLwJrutGoHSQXCh7u4o2t1drG+c0a9Flnqww6XUKSfQMPpJBRjU8d4RXB09qtvaA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", + "integrity": "sha512-EdRAaAyk2cUE1wOf2DkEhzxqOQvFOoRJFNS6NeyJ01Gp2beMRpBAINjM2iDXE3KCuKhwnvHIQCJm6ThL2Z+HzQ==", "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], "dependencies": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" + "escalade": "^3.1.2", + "picocolors": "^1.0.1" }, "bin": { "update-browserslist-db": "cli.js" diff --git a/frontend/package.json b/frontend/package.json index 6741a1b4..258c5c27 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -2,11 +2,10 @@ "name": "frontend", "private": true, "version": "0.0.0", - "type": "module", "scripts": { - "dev": "vite", + "dev": "vite --host", "build": "tsc && vite build", - "preview": "vite preview" + "preview": "vite preview --host" }, "dependencies": { "@fluentui/react-components": "^9.47.2", @@ -45,6 +44,7 @@ "uuid": "^9.0.0" }, "devDependencies": { + "@ianvs/prettier-plugin-sort-imports": "^4.3.1", "@tailwindcss/typography": "^0.5.10", "@types/file-saver": "^2.0.7", "@types/lodash-es": "^4.17.12", @@ -55,6 +55,8 @@ "@vitejs/plugin-react": "^4.0.0", "autoprefixer": "^10.4.14", "postcss": "^8.4.23", + "prettier": "^3.3.3", + "prettier-plugin-tailwindcss": "^0.6.6", "rollup-plugin-visualizer": "^5.9.0", "sass": "^1.62.1", "tailwindcss": "^3.3.2", diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js index 2e7af2b7..33ad091d 100644 --- a/frontend/postcss.config.js +++ b/frontend/postcss.config.js @@ -1,4 +1,4 @@ -export default { +module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, diff --git a/frontend/prettier.config.js b/frontend/prettier.config.js new file mode 100644 index 00000000..49068690 --- /dev/null +++ b/frontend/prettier.config.js @@ -0,0 +1,19 @@ +/** @type {import('prettier').Config} */ +module.exports = { + endOfLine: 'lf', + semi: false, + singleQuote: true, + tabWidth: 2, + trailingComma: 'es5', + importOrder: ['^(react/(.*)$)|^(react$)', '', '^[./]'], + importOrderSeparation: false, + importOrderSortSpecifiers: true, + importOrderBuiltinModulesToTop: true, + importOrderParserPlugins: ['typescript', 'jsx', 'decorators-legacy'], + importOrderMergeDuplicateImports: true, + importOrderCombineTypeAndValueImports: true, + plugins: [ + '@ianvs/prettier-plugin-sort-imports', + 'prettier-plugin-tailwindcss', + ], +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f4e847f1..85803e07 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -23,77 +23,129 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -import { FluentProvider, Tab, TabList, webDarkTheme, webLightTheme } from '@fluentui/react-components'; -import { FC, useEffect, useState } from 'react'; -import { Route, Routes, useLocation, useNavigate } from 'react-router'; -import { pages as clientPages } from './pages'; -import { useMediaQuery } from 'usehooks-ts'; -import commonStore from './stores/commonStore'; -import { observer } from 'mobx-react-lite'; -import { useTranslation } from 'react-i18next'; -import { CustomToastContainer } from './components/CustomToastContainer'; -import { LazyImportComponent } from './components/LazyImportComponent'; +import { FC, useEffect, useState } from 'react' +import { + FluentProvider, + Tab, + TabList, + webDarkTheme, + webLightTheme, +} from '@fluentui/react-components' +import { observer } from 'mobx-react-lite' +import { useTranslation } from 'react-i18next' +import { Route, Routes, useLocation, useNavigate } from 'react-router' +import { useMediaQuery } from 'usehooks-ts' +import { CustomToastContainer } from './components/CustomToastContainer' +import { LazyImportComponent } from './components/LazyImportComponent' +import { MobileFloatingNavigator } from './components/MobileFloatingNavigator' +import { pages as clientPages } from './pages' +import commonStore from './stores/commonStore' const App: FC = observer(() => { - const { t } = useTranslation(); - const navigate = useNavigate(); - const location = useLocation(); - const mq = useMediaQuery('(min-width: 640px)'); - const pages = commonStore.platform === 'web' ? clientPages.filter(page => - !['/configs', '/models', '/downloads', '/train', '/about'].some(path => page.path === path) - ) : clientPages; + const { t } = useTranslation() + const navigate = useNavigate() + const location = useLocation() + const mq = useMediaQuery('(min-width: 640px)') - const [path, setPath] = useState(pages[0].path); + const isWeb = commonStore.platform === 'web' + const screenWidthSmallerThan640 = !mq + const useMobileStyle = isWeb && screenWidthSmallerThan640 + + const pages = isWeb + ? clientPages.filter( + (page) => + !['/configs', '/models', '/downloads', '/train', '/about'].some( + (path) => page.path === path + ) + ) + : clientPages + + const [path, setPath] = useState(pages[0].path) + const isHome = path === '/' const selectTab = (selectedPath: unknown) => - typeof selectedPath === 'string' ? navigate({ pathname: selectedPath }) : null; + typeof selectedPath === 'string' + ? navigate({ pathname: selectedPath }) + : null + + useEffect(() => setPath(location.pathname), [location]) - useEffect(() => setPath(location.pathname), [location]); + const topTabList = ( + selectTab(value)} + vertical + > + {pages + .filter((page) => page.top) + .map(({ label, path, icon }, index) => ( + + {mq && t(label)} + + ))} + + ) + const bottomTabList = ( + selectTab(value)} + vertical + > + {pages + .filter((page) => !page.top) + .map(({ label, path, icon }, index) => ( + + {mq && t(label)} + + ))} + + ) return ( + data-theme={commonStore.settings.darkMode ? 'dark' : 'light'} + >
-
- selectTab(value)} - vertical - > - {pages.filter(page => page.top).map(({ label, path, icon }, index) => ( - - {mq && t(label)} - - ))} - - selectTab(value)} - vertical - > - {pages.filter(page => !page.top).map(({ label, path, icon }, index) => ( - - {mq && t(label)} - - ))} - -
-
+ {useMobileStyle ? ( + !isHome ? ( + + ) : ( + <> + ) + ) : ( +
+ {topTabList} + {bottomTabList} +
+ )} +
{pages.map(({ path, element }, index) => ( - } /> + } + /> ))}
- ); -}); + ) +}) -export default App; +export default App diff --git a/frontend/src/_locales/i18n-react.ts b/frontend/src/_locales/i18n-react.ts index a04e2799..596f3021 100644 --- a/frontend/src/_locales/i18n-react.ts +++ b/frontend/src/_locales/i18n-react.ts @@ -1,13 +1,16 @@ -import i18n, { changeLanguage } from 'i18next'; -import { initReactI18next } from 'react-i18next'; -import { resources } from './resources'; -import { getUserLanguage } from '../utils'; +import i18n, { changeLanguage } from 'i18next' +import { initReactI18next } from 'react-i18next' +import { getUserLanguage } from '../utils' +import { resources } from './resources' -i18n.use(initReactI18next).init({ - resources, - interpolation: { - escapeValue: false // not needed for react as it escapes by default - } -}).then(() => { - changeLanguage(getUserLanguage()); -}); +i18n + .use(initReactI18next) + .init({ + resources, + interpolation: { + escapeValue: false, // not needed for react as it escapes by default + }, + }) + .then(() => { + changeLanguage(getUserLanguage()) + }) diff --git a/frontend/src/_locales/i18n.ts b/frontend/src/_locales/i18n.ts index dc30d1b7..f351c4e7 100644 --- a/frontend/src/_locales/i18n.ts +++ b/frontend/src/_locales/i18n.ts @@ -1,9 +1,11 @@ -import i18n, { changeLanguage } from 'i18next'; -import { resources } from './resources'; -import { getUserLanguage } from '../utils'; +import i18n, { changeLanguage } from 'i18next' +import { getUserLanguage } from '../utils' +import { resources } from './resources' -i18n.init({ - resources -}).then(() => { - changeLanguage(getUserLanguage()); -}); +i18n + .init({ + resources, + }) + .then(() => { + changeLanguage(getUserLanguage()) + }) diff --git a/frontend/src/_locales/ja/main.json b/frontend/src/_locales/ja/main.json index c9389e85..02871479 100644 --- a/frontend/src/_locales/ja/main.json +++ b/frontend/src/_locales/ja/main.json @@ -363,5 +363,11 @@ "File format of the model or state model not supported": "モデルまたはStateモデルのファイル形式がサポートされていません", "Note: You are using an English state": "注意: あなたは英語のstateを使用しています", "Note: You are using a Chinese state": "注意: あなたは中国語のstateを使用しています", - "Note: You are using a Japanese state": "注意: あなたは日本語のstateを使用しています" -} \ No newline at end of file + "Note: You are using a Japanese state": "注意: あなたは日本語のstateを使用しています", + "What's the weather like in Paris?": "パリの天気はどうですか?", + "Function Call": "関数呼び出し", + "Tool Definition": "ツール定義", + "Tool Return Value": "ツールの戻り値", + "Tool Definition is not a valid JSON": "ツール定義が有効なJSONではありません", + "Current selected model may not support function call": "現在選択されているモデルは、関数呼び出しをサポートしていない可能性があります" +} diff --git a/frontend/src/_locales/resources.ts b/frontend/src/_locales/resources.ts index 37ca7759..e5768a5f 100644 --- a/frontend/src/_locales/resources.ts +++ b/frontend/src/_locales/resources.ts @@ -1,9 +1,9 @@ -import zhHans from './zh-hans/main.json'; -import ja from './ja/main.json'; +import ja from './ja/main.json' +import zhHans from './zh-hans/main.json' export const resources = { zh: { - translation: zhHans + translation: zhHans, }, // de: { // translation: de, @@ -21,8 +21,8 @@ export const resources = { // translation: it, // }, ja: { - translation: ja - } + translation: ja, + }, // ko: { // translation: ko, // }, @@ -35,4 +35,4 @@ export const resources = { // zhHant: { // translation: zhHant, // }, -}; +} diff --git a/frontend/src/_locales/zh-hans/main.json b/frontend/src/_locales/zh-hans/main.json index 0e26ea6e..c1cc1c7e 100644 --- a/frontend/src/_locales/zh-hans/main.json +++ b/frontend/src/_locales/zh-hans/main.json @@ -363,5 +363,11 @@ "File format of the model or state model not supported": "模型或state模型的文件格式不支持", "Note: You are using an English state": "注意: 你正在使用一个英文state", "Note: You are using a Chinese state": "注意: 你正在使用一个中文state", - "Note: You are using a Japanese state": "注意: 你正在使用一个日文state" -} \ No newline at end of file + "Note: You are using a Japanese state": "注意: 你正在使用一个日文state", + "What's the weather like in Paris?": "巴黎的天气怎么样?", + "Function Call": "函数调用", + "Tool Definition": "工具定义", + "Tool Return Value": "工具返回值", + "Tool Definition is not a valid JSON": "工具定义不是一个有效的JSON", + "Current selected model may not support function call": "当前选择的模型可能不支持函数调用" +} diff --git a/frontend/src/apis/index.ts b/frontend/src/apis/index.ts index ab8972ea..a59b529e 100644 --- a/frontend/src/apis/index.ts +++ b/frontend/src/apis/index.ts @@ -1,73 +1,90 @@ -import commonStore, { Status } from '../stores/commonStore'; -import { toast } from 'react-toastify'; -import { TFunction } from 'i18next'; +import { TFunction } from 'i18next' +import { toast } from 'react-toastify' +import commonStore, { Status } from '../stores/commonStore' export const readRoot = async () => { - const port = commonStore.getCurrentModelConfig().apiParameters.apiPort; - return fetch(`http://127.0.0.1:${port}`); -}; + const port = commonStore.getCurrentModelConfig().apiParameters.apiPort + return fetch(`http://127.0.0.1:${port}`) +} export const exit = async (timeout?: number) => { - const controller = new AbortController(); - if (timeout) - setTimeout(() => controller.abort(), timeout); + const controller = new AbortController() + if (timeout) setTimeout(() => controller.abort(), timeout) - const port = commonStore.getCurrentModelConfig().apiParameters.apiPort; - return fetch(`http://127.0.0.1:${port}/exit`, { method: 'POST', signal: controller.signal }); -}; + const port = commonStore.getCurrentModelConfig().apiParameters.apiPort + return fetch(`http://127.0.0.1:${port}/exit`, { + method: 'POST', + signal: controller.signal, + }) +} export const switchModel = async (body: any) => { - const port = commonStore.getCurrentModelConfig().apiParameters.apiPort; + const port = commonStore.getCurrentModelConfig().apiParameters.apiPort return fetch(`http://127.0.0.1:${port}/switch-model`, { method: 'POST', headers: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }, - body: JSON.stringify(body) - }); -}; + body: JSON.stringify(body), + }) +} -export const updateConfig = async (t: TFunction<'translation', undefined, 'translation'>, body: any) => { +export const updateConfig = async ( + t: TFunction<'translation', undefined, 'translation'>, + body: any +) => { if (body.state) { - const stateName = body.state.toLowerCase(); - if (commonStore.settings.language !== 'zh' && (stateName.includes('chn') || stateName.includes('chinese'))) { + const stateName = body.state.toLowerCase() + if ( + commonStore.settings.language !== 'zh' && + (stateName.includes('chn') || stateName.includes('chinese')) + ) { toast(t('Note: You are using a Chinese state'), { type: 'warning', - toastId: 'state_warning' - }); - } else if (commonStore.settings.language !== 'dev' && (stateName.includes('eng') || stateName.includes('english'))) { + toastId: 'state_warning', + }) + } else if ( + commonStore.settings.language !== 'dev' && + (stateName.includes('eng') || stateName.includes('english')) + ) { toast(t('Note: You are using an English state'), { type: 'warning', - toastId: 'state_warning' - }); - } else if (commonStore.settings.language !== 'ja' && (stateName.includes('jpn') || stateName.includes('japanese'))) { + toastId: 'state_warning', + }) + } else if ( + commonStore.settings.language !== 'ja' && + (stateName.includes('jpn') || stateName.includes('japanese')) + ) { toast(t('Note: You are using a Japanese state'), { type: 'warning', - toastId: 'state_warning' - }); + toastId: 'state_warning', + }) } } - const port = commonStore.getCurrentModelConfig().apiParameters.apiPort; + const port = commonStore.getCurrentModelConfig().apiParameters.apiPort return fetch(`http://127.0.0.1:${port}/update-config`, { method: 'POST', headers: { - 'Content-Type': 'application/json' + 'Content-Type': 'application/json', }, - body: JSON.stringify(body) - }); -}; + body: JSON.stringify(body), + }) +} -export const getStatus = async (timeout?: number): Promise => { - const controller = new AbortController(); - if (timeout) - setTimeout(() => controller.abort(), timeout); +export const getStatus = async ( + timeout?: number +): Promise => { + const controller = new AbortController() + if (timeout) setTimeout(() => controller.abort(), timeout) - const port = commonStore.getCurrentModelConfig().apiParameters.apiPort; - let ret: Status | undefined; - await fetch(`http://127.0.0.1:${port}/status`, { signal: controller.signal }).then(r => r.json()).then(data => { - ret = data; - }).catch(() => { - }); - return ret; -}; + const port = commonStore.getCurrentModelConfig().apiParameters.apiPort + let ret: Status | undefined + await fetch(`http://127.0.0.1:${port}/status`, { signal: controller.signal }) + .then((r) => r.json()) + .then((data) => { + ret = data + }) + .catch(() => {}) + return ret +} diff --git a/frontend/src/components/ConfigSelector.tsx b/frontend/src/components/ConfigSelector.tsx index 1be1f0fd..ae21e7cd 100644 --- a/frontend/src/components/ConfigSelector.tsx +++ b/frontend/src/components/ConfigSelector.tsx @@ -1,24 +1,32 @@ -import { FC } from 'react'; -import { observer } from 'mobx-react-lite'; -import { Dropdown, Option, PresenceBadge } from '@fluentui/react-components'; -import commonStore from '../stores/commonStore'; +import { FC } from 'react' +import { Dropdown, Option, PresenceBadge } from '@fluentui/react-components' +import { observer } from 'mobx-react-lite' +import commonStore from '../stores/commonStore' -export const ConfigSelector: FC<{ size?: 'small' | 'medium' | 'large' }> = observer(({ size }) => { - return { - if (data.optionValue) - commonStore.setCurrentConfigIndex(Number(data.optionValue)); - }}> - {commonStore.modelConfigs.map((config, index) => - - )} - ; -}); \ No newline at end of file +export const ConfigSelector: FC<{ size?: 'small' | 'medium' | 'large' }> = + observer(({ size }) => { + return ( + { + if (data.optionValue) + commonStore.setCurrentConfigIndex(Number(data.optionValue)) + }} + > + {commonStore.modelConfigs.map((config, index) => ( + + ))} + + ) + }) diff --git a/frontend/src/components/CopyButton.tsx b/frontend/src/components/CopyButton.tsx index 7dc3304f..502c4efe 100644 --- a/frontend/src/components/CopyButton.tsx +++ b/frontend/src/components/CopyButton.tsx @@ -1,26 +1,34 @@ -import { FC, useState } from 'react'; -import { CheckIcon, CopyIcon } from '@primer/octicons-react'; -import { useTranslation } from 'react-i18next'; -import { ClipboardSetText } from '../../wailsjs/runtime'; -import { ToolTipButton } from './ToolTipButton'; +import { FC, useState } from 'react' +import { CheckIcon, CopyIcon } from '@primer/octicons-react' +import { useTranslation } from 'react-i18next' +import { ClipboardSetText } from '../../wailsjs/runtime' +import { ToolTipButton } from './ToolTipButton' -export const CopyButton: FC<{ content: string, showDelay?: number, }> = ({ content, showDelay = 0 }) => { - const { t } = useTranslation(); - const [copied, setCopied] = useState(false); +export const CopyButton: FC<{ content: string; showDelay?: number }> = ({ + content, + showDelay = 0, +}) => { + const { t } = useTranslation() + const [copied, setCopied] = useState(false) const onClick = () => { ClipboardSetText(content) - .then(() => setCopied(true)) - .then(() => - setTimeout(() => { - setCopied(false); - }, 600) - ); - }; + .then(() => setCopied(true)) + .then(() => + setTimeout(() => { + setCopied(false) + }, 600) + ) + } return ( - : } - onClick={onClick} /> - ); -}; + onClick={onClick} + /> + ) +} diff --git a/frontend/src/components/CustomToastContainer.tsx b/frontend/src/components/CustomToastContainer.tsx index eb8e6ca3..6f9a4557 100644 --- a/frontend/src/components/CustomToastContainer.tsx +++ b/frontend/src/components/CustomToastContainer.tsx @@ -1,7 +1,7 @@ -import commonStore from '../stores/commonStore'; -import { ToastContainer } from 'react-toastify'; +import { ToastContainer } from 'react-toastify' +import commonStore from '../stores/commonStore' -export const CustomToastContainer = () => +export const CustomToastContainer = () => ( pauseOnFocusLoss={false} draggable={false} theme={commonStore.settings.darkMode ? 'dark' : 'light'} - />; \ No newline at end of file + /> +) diff --git a/frontend/src/components/DialogButton.tsx b/frontend/src/components/DialogButton.tsx index 1e65499b..877269bd 100644 --- a/frontend/src/components/DialogButton.tsx +++ b/frontend/src/components/DialogButton.tsx @@ -1,4 +1,4 @@ -import React, { FC, ReactElement } from 'react'; +import React, { FC, ReactElement } from 'react' import { Button, Dialog, @@ -7,75 +7,102 @@ import { DialogContent, DialogSurface, DialogTitle, - DialogTrigger -} from '@fluentui/react-components'; -import { ToolTipButton } from './ToolTipButton'; -import { useTranslation } from 'react-i18next'; -import { LazyImportComponent } from './LazyImportComponent'; + DialogTrigger, +} from '@fluentui/react-components' +import { useTranslation } from 'react-i18next' +import { LazyImportComponent } from './LazyImportComponent' +import { ToolTipButton } from './ToolTipButton' -const MarkdownRender = React.lazy(() => import('./MarkdownRender')); +const MarkdownRender = React.lazy(() => import('./MarkdownRender')) export const DialogButton: FC<{ - text?: string | null, - icon?: ReactElement, - tooltip?: string | null, - className?: string, - title: string, + text?: string | null + icon?: ReactElement + tooltip?: string | null + className?: string + title: string content?: string | ReactElement | null - markdown?: boolean, - onConfirm?: () => void, - size?: 'small' | 'medium' | 'large', - shape?: 'rounded' | 'circular' | 'square', - appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent', - cancelButton?: boolean, - confirmButton?: boolean, - cancelButtonText?: string, - confirmButtonText?: string, + markdown?: boolean + onConfirm?: () => void + size?: 'small' | 'medium' | 'large' + shape?: 'rounded' | 'circular' | 'square' + appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent' + cancelButton?: boolean + confirmButton?: boolean + cancelButtonText?: string + confirmButtonText?: string }> = ({ - text, icon, tooltip, className, title, content, markdown, - onConfirm, size, shape, appearance, + text, + icon, + tooltip, + className, + title, + content, + markdown, + onConfirm, + size, + shape, + appearance, cancelButton = true, confirmButton = true, cancelButtonText = 'Cancel', - confirmButtonText = 'Confirm' + confirmButtonText = 'Confirm', }) => { - const { t } = useTranslation(); + const { t } = useTranslation() - return - - {tooltip ? - : - - } - - - - {title} - - { - markdown ? + return ( + + + {tooltip ? ( + + ) : ( + + )} + + + + {title} + + {markdown ? ( {content} - : + + ) : ( content - } - - - {cancelButton && ( - - - - )} - {confirmButton && ( - - - - )} - - - - ; -}; \ No newline at end of file + )} + + + {cancelButton && ( + + + + )} + {confirmButton && ( + + + + )} + + + + + ) +} diff --git a/frontend/src/components/Labeled.tsx b/frontend/src/components/Labeled.tsx index d315c111..4dee13ee 100644 --- a/frontend/src/components/Labeled.tsx +++ b/frontend/src/components/Labeled.tsx @@ -1,15 +1,15 @@ -import { FC, ReactElement } from 'react'; -import { Label, Tooltip } from '@fluentui/react-components'; -import classnames from 'classnames'; +import { FC, ReactElement } from 'react' +import { Label, Tooltip } from '@fluentui/react-components' +import classnames from 'classnames' export const Labeled: FC<{ - label: string; - desc?: string | null, - descComponent?: ReactElement, - content: ReactElement, - flex?: boolean, - spaceBetween?: boolean, - breakline?: boolean, + label: string + desc?: string | null + descComponent?: ReactElement + content: ReactElement + flex?: boolean + spaceBetween?: boolean + breakline?: boolean onMouseEnter?: () => void onMouseLeave?: () => void }> = ({ @@ -21,22 +21,34 @@ export const Labeled: FC<{ spaceBetween, breakline, onMouseEnter, - onMouseLeave + onMouseLeave, }) => { return ( -
- {(desc || descComponent) ? - - - : - - } +
+ {desc || descComponent ? ( + + + + ) : ( + + )} {content}
- ); -}; + ) +} diff --git a/frontend/src/components/LazyImportComponent.tsx b/frontend/src/components/LazyImportComponent.tsx index 17f8d0f7..f94e4249 100644 --- a/frontend/src/components/LazyImportComponent.tsx +++ b/frontend/src/components/LazyImportComponent.tsx @@ -1,24 +1,27 @@ -import { FC, LazyExoticComponent, ReactNode, Suspense } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Spinner } from '@fluentui/react-components'; +import { FC, LazyExoticComponent, ReactNode, Suspense } from 'react' +import { Spinner } from '@fluentui/react-components' +import { useTranslation } from 'react-i18next' interface LazyImportComponentProps { - lazyChildren: LazyExoticComponent>; - lazyProps?: any; - children?: ReactNode; + lazyChildren: LazyExoticComponent> + lazyProps?: any + children?: ReactNode } export const LazyImportComponent: FC = (props) => { - const { t } = useTranslation(); + const { t } = useTranslation() return ( - - -
}> + + +
+ } + > {props.children} - ); -}; \ No newline at end of file + ) +} diff --git a/frontend/src/components/MarkdownRender.tsx b/frontend/src/components/MarkdownRender.tsx index 6a811361..50008e45 100644 --- a/frontend/src/components/MarkdownRender.tsx +++ b/frontend/src/components/MarkdownRender.tsx @@ -1,37 +1,45 @@ -import 'katex/dist/katex.min.css'; -import ReactMarkdown from 'react-markdown'; -import rehypeRaw from 'rehype-raw'; -import rehypeHighlight from 'rehype-highlight'; -import rehypeKatex from 'rehype-katex'; -import remarkMath from 'remark-math'; -import remarkGfm from 'remark-gfm'; -import remarkBreaks from 'remark-breaks'; -import { FC } from 'react'; -import { ReactMarkdownOptions } from 'react-markdown/lib/react-markdown'; -import { BrowserOpenURL } from '../../wailsjs/runtime'; +import 'katex/dist/katex.min.css' +import { FC } from 'react' +import ReactMarkdown from 'react-markdown' +import { ReactMarkdownOptions } from 'react-markdown/lib/react-markdown' +import rehypeHighlight from 'rehype-highlight' +import rehypeKatex from 'rehype-katex' +import rehypeRaw from 'rehype-raw' +import remarkBreaks from 'remark-breaks' +import remarkGfm from 'remark-gfm' +import remarkMath from 'remark-math' +import { BrowserOpenURL } from '../../wailsjs/runtime' const Hyperlink: FC = ({ href, children }) => { return ( { - BrowserOpenURL(href); + BrowserOpenURL(href) }} > {/*@ts-ignore*/} {children} - ); -}; + ) +} -const MarkdownRender: FC = (props) => { +const MarkdownRender: FC = ( + props +) => { return ( -
- {props.disabled ? +
+ {props.disabled ? (
{props.children} -
: - + ) : ( + = (props 's', 'a', 'pre', - 'cite' + 'cite', ]} unwrapDisallowed={true} remarkPlugins={[remarkMath, remarkGfm, remarkBreaks]} @@ -101,19 +109,19 @@ const MarkdownRender: FC = (props rehypeHighlight, { detect: true, - ignoreMissing: true - } - ] + ignoreMissing: true, + }, + ], ]} components={{ - a: Hyperlink + a: Hyperlink, }} > {props.children} - } + )}
- ); -}; + ) +} -export default MarkdownRender; +export default MarkdownRender diff --git a/frontend/src/components/MobileFloatingNavigator.tsx b/frontend/src/components/MobileFloatingNavigator.tsx new file mode 100644 index 00000000..b6b66f68 --- /dev/null +++ b/frontend/src/components/MobileFloatingNavigator.tsx @@ -0,0 +1,113 @@ +import { FC, ReactElement, useEffect, useRef, useState } from 'react' +import { Button } from '@fluentui/react-components' +import { ArrowRight20Regular } from '@fluentui/react-icons' +import classNames from 'classnames' +import { observer } from 'mobx-react-lite' +import commonStore from '../stores/commonStore' + +export const MobileFloatingNavigator: FC<{ + autoHideDelay?: number + topTabList: ReactElement + bottomTabList: ReactElement +}> = observer(({ autoHideDelay = 3000, topTabList, bottomTabList }) => { + const useDarkMode = commonStore.settings.darkMode + const [expanded, setExpanded] = useState(true) + const ref = useRef(null) + const timeout = useRef(autoHideDelay) + + useEffect(() => { + const timer = setInterval(() => { + if (timeout.current > 0) { + timeout.current -= 300 + } else { + setExpanded(false) + } + }, 300) + return () => { + clearInterval(timer) + } + }, []) + + useEffect(() => { + const listener = (e: UIEvent) => { + if (ref.current) { + if (ref.current.contains(e.target as Node)) { + timeout.current = autoHideDelay + } else { + setExpanded(false) + } + } + } + document.addEventListener('mousedown', listener) + document.addEventListener('touchstart', listener) + return () => { + document.removeEventListener('mousedown', listener) + document.removeEventListener('touchstart', listener) + } + }, []) + + const contentRef = useRef(null) + const [height, setHeight] = useState(0) + + useEffect(() => { + const updateHeight = () => { + setHeight(contentRef.current?.scrollHeight || 0) + } + const observer = new ResizeObserver(updateHeight) + observer.observe(contentRef.current!) + return () => observer.disconnect() + }, []) + + return ( +
+
+
+ {expanded ? ( + <> + {topTabList} +
+ {bottomTabList} + + ) : ( + + )} +
+
+
+ ) +}) diff --git a/frontend/src/components/NumberInput.tsx b/frontend/src/components/NumberInput.tsx index dafdaa1d..575d5ad0 100644 --- a/frontend/src/components/NumberInput.tsx +++ b/frontend/src/components/NumberInput.tsx @@ -1,33 +1,45 @@ -import React, { CSSProperties, FC } from 'react'; -import { Input } from '@fluentui/react-components'; -import { SliderOnChangeData } from '@fluentui/react-slider'; +import React, { CSSProperties, FC } from 'react' +import { Input } from '@fluentui/react-components' +import { SliderOnChangeData } from '@fluentui/react-slider' export const NumberInput: FC<{ - value: number, - min: number, - max: number, - step?: number, - onChange?: (ev: React.ChangeEvent, data: SliderOnChangeData) => void - style?: CSSProperties, + value: number + min: number + max: number + step?: number + onChange?: ( + ev: React.ChangeEvent, + data: SliderOnChangeData + ) => void + style?: CSSProperties toFixed?: number disabled?: boolean }> = ({ value, min, max, step, onChange, style, toFixed = 2, disabled }) => { return ( - { - onChange?.(e, { value: Number(data.value) }); + onChange?.(e, { value: Number(data.value) }) }} onBlur={(e) => { if (onChange) { if (step) { - const offset = (min > 0 ? min : 0) - (max < 0 ? max : 0); - value = Number((( - Math.round((value - offset) / step) * step) - + offset) - .toFixed(toFixed)); // avoid precision issues + const offset = (min > 0 ? min : 0) - (max < 0 ? max : 0) + value = Number( + (Math.round((value - offset) / step) * step + offset).toFixed( + toFixed + ) + ) // avoid precision issues } - onChange(e, { value: Math.max(Math.min(value, max), min) }); + onChange(e, { value: Math.max(Math.min(value, max), min) }) } - }} /> - ); -}; + }} + /> + ) +} diff --git a/frontend/src/components/Page.tsx b/frontend/src/components/Page.tsx index f835a241..86e1e503 100644 --- a/frontend/src/components/Page.tsx +++ b/frontend/src/components/Page.tsx @@ -1,12 +1,15 @@ -import React, { FC, ReactElement } from 'react'; -import { Divider, Text } from '@fluentui/react-components'; +import React, { FC, ReactElement } from 'react' +import { Divider, Text } from '@fluentui/react-components' -export const Page: FC<{ title: string; content: ReactElement }> = ({ title, content }) => { +export const Page: FC<{ title: string; content: ReactElement }> = ({ + title, + content, +}) => { return ( -
+
{title} {content}
- ); -}; + ) +} diff --git a/frontend/src/components/ReadButton.tsx b/frontend/src/components/ReadButton.tsx index 2c019752..0a86b563 100644 --- a/frontend/src/components/ReadButton.tsx +++ b/frontend/src/components/ReadButton.tsx @@ -1,70 +1,73 @@ -import { FC, useState } from 'react'; -import { MuteIcon, UnmuteIcon } from '@primer/octicons-react'; -import { useTranslation } from 'react-i18next'; -import { ToolTipButton } from './ToolTipButton'; -import commonStore from '../stores/commonStore'; -import { observer } from 'mobx-react-lite'; +import { FC, useState } from 'react' +import { MuteIcon, UnmuteIcon } from '@primer/octicons-react' +import { observer } from 'mobx-react-lite' +import { useTranslation } from 'react-i18next' +import commonStore from '../stores/commonStore' +import { ToolTipButton } from './ToolTipButton' -const synth = window.speechSynthesis; +const synth = window.speechSynthesis export const ReadButton: FC<{ - content: string, - inSpeaking?: boolean, - showDelay?: number, + content: string + inSpeaking?: boolean + showDelay?: number setSpeakingOuter?: (speaking: boolean) => void -}> = observer(({ - content, - inSpeaking = false, - showDelay = 0, - setSpeakingOuter -}) => { - const { t } = useTranslation(); - const [speaking, setSpeaking] = useState(inSpeaking); - let lang: string = commonStore.settings.language; - if (lang === 'dev') - lang = 'en'; +}> = observer( + ({ content, inSpeaking = false, showDelay = 0, setSpeakingOuter }) => { + const { t } = useTranslation() + const [speaking, setSpeaking] = useState(inSpeaking) + let lang: string = commonStore.settings.language + if (lang === 'dev') lang = 'en' - const setSpeakingInner = (speaking: boolean) => { - setSpeakingOuter?.(speaking); - setSpeaking(speaking); - }; + const setSpeakingInner = (speaking: boolean) => { + setSpeakingOuter?.(speaking) + setSpeaking(speaking) + } - const startSpeak = () => { - synth.cancel(); + const startSpeak = () => { + synth.cancel() - const utterance = new SpeechSynthesisUtterance(content); - const voices = synth.getVoices(); + const utterance = new SpeechSynthesisUtterance(content) + const voices = synth.getVoices() - let voice; - if (lang === 'en') - voice = voices.find((v) => v.name.toLowerCase().includes('microsoft aria')); - else if (lang === 'zh') - voice = voices.find((v) => v.name.toLowerCase().includes('xiaoyi')); - else if (lang === 'ja') - voice = voices.find((v) => v.name.toLowerCase().includes('nanami')); - if (!voice) voice = voices.find((v) => v.lang.substring(0, 2) === lang); - if (!voice) voice = voices.find((v) => v.lang === navigator.language); + let voice + if (lang === 'en') + voice = voices.find((v) => + v.name.toLowerCase().includes('microsoft aria') + ) + else if (lang === 'zh') + voice = voices.find((v) => v.name.toLowerCase().includes('xiaoyi')) + else if (lang === 'ja') + voice = voices.find((v) => v.name.toLowerCase().includes('nanami')) + if (!voice) voice = voices.find((v) => v.lang.substring(0, 2) === lang) + if (!voice) voice = voices.find((v) => v.lang === navigator.language) - Object.assign(utterance, { - rate: 1, - volume: 1, - onend: () => setSpeakingInner(false), - onerror: () => setSpeakingInner(false), - voice: voice - }); + Object.assign(utterance, { + rate: 1, + volume: 1, + onend: () => setSpeakingInner(false), + onerror: () => setSpeakingInner(false), + voice: voice, + }) - synth.speak(utterance); - setSpeakingInner(true); - }; + synth.speak(utterance) + setSpeakingInner(true) + } - const stopSpeak = () => { - synth.cancel(); - setSpeakingInner(false); - }; + const stopSpeak = () => { + synth.cancel() + setSpeakingInner(false) + } - return ( - : } - onClick={speaking ? stopSpeak : startSpeak} /> - ); -}); + return ( + : } + onClick={speaking ? stopSpeak : startSpeak} + /> + ) + } +) diff --git a/frontend/src/components/ResetConfigsButton.tsx b/frontend/src/components/ResetConfigsButton.tsx index ad9c9918..8068deb1 100644 --- a/frontend/src/components/ResetConfigsButton.tsx +++ b/frontend/src/components/ResetConfigsButton.tsx @@ -1,18 +1,35 @@ -import React, { FC } from 'react'; -import { DialogButton } from './DialogButton'; -import { useTranslation } from 'react-i18next'; -import { ArrowReset20Regular } from '@fluentui/react-icons'; -import commonStore from '../stores/commonStore'; +import React, { FC } from 'react' +import { ArrowReset20Regular } from '@fluentui/react-icons' +import { useTranslation } from 'react-i18next' +import { + defaultModelConfigs, + defaultModelConfigsMac, +} from '../pages/defaultConfigs' +import commonStore from '../stores/commonStore' +import { DialogButton } from './DialogButton' -import { defaultModelConfigs, defaultModelConfigsMac } from '../pages/defaultConfigs'; - -export const ResetConfigsButton: FC<{ afterConfirm?: () => void }> = ({ afterConfirm }) => { - const { t } = useTranslation(); - return } tooltip={t('Reset All Configs')} title={t('Reset All Configs')} - content={t('Are you sure you want to reset all configs? This will obtain the latest preset configs, but will override your custom configs and cannot be undone.')} - onConfirm={() => { - commonStore.setModelConfigs(commonStore.platform !== 'darwin' ? defaultModelConfigs : defaultModelConfigsMac, false); - commonStore.setCurrentConfigIndex(0, true); - afterConfirm?.(); - }} />; -}; \ No newline at end of file +export const ResetConfigsButton: FC<{ afterConfirm?: () => void }> = ({ + afterConfirm, +}) => { + const { t } = useTranslation() + return ( + } + tooltip={t('Reset All Configs')} + title={t('Reset All Configs')} + content={t( + 'Are you sure you want to reset all configs? This will obtain the latest preset configs, but will override your custom configs and cannot be undone.' + )} + onConfirm={() => { + commonStore.setModelConfigs( + commonStore.platform !== 'darwin' + ? defaultModelConfigs + : defaultModelConfigsMac, + false + ) + commonStore.setCurrentConfigIndex(0, true) + afterConfirm?.() + }} + /> + ) +} diff --git a/frontend/src/components/RunButton.tsx b/frontend/src/components/RunButton.tsx index 8810901c..2b92f26d 100644 --- a/frontend/src/components/RunButton.tsx +++ b/frontend/src/components/RunButton.tsx @@ -1,359 +1,482 @@ -import React, { FC, MouseEventHandler, ReactElement } from 'react'; -import commonStore, { ModelStatus } from '../stores/commonStore'; +import React, { FC, MouseEventHandler, ReactElement } from 'react' +import { Button } from '@fluentui/react-components' +import { Play16Regular, Stop16Regular } from '@fluentui/react-icons' +import { observer } from 'mobx-react-lite' +import { useTranslation } from 'react-i18next' +import { useNavigate } from 'react-router' +import { toast } from 'react-toastify' import { AddToDownloadList, FileExists, IsPortAvailable, StartServer, - StartWebGPUServer -} from '../../wailsjs/go/backend_golang/App'; -import { Button } from '@fluentui/react-components'; -import { observer } from 'mobx-react-lite'; -import { exit, getStatus, readRoot, switchModel, updateConfig } from '../apis'; -import { toast } from 'react-toastify'; -import { checkDependencies, getHfDownloadUrl, getStrategy, toastWithButton } from '../utils'; -import { useTranslation } from 'react-i18next'; -import { ToolTipButton } from './ToolTipButton'; -import { Play16Regular, Stop16Regular } from '@fluentui/react-icons'; -import { useNavigate } from 'react-router'; -import { WindowShow } from '../../wailsjs/runtime'; -import { convertToGGML, convertToSt } from '../utils/convert-model'; -import { Precision } from '../types/configs'; -import { defaultCompositionABCPrompt, defaultCompositionPrompt } from '../pages/defaultConfigs'; + StartWebGPUServer, +} from '../../wailsjs/go/backend_golang/App' +import { WindowShow } from '../../wailsjs/runtime' +import { exit, getStatus, readRoot, switchModel, updateConfig } from '../apis' +import { + defaultCompositionABCPrompt, + defaultCompositionPrompt, +} from '../pages/defaultConfigs' +import commonStore, { ModelStatus } from '../stores/commonStore' +import { Precision } from '../types/configs' +import { + checkDependencies, + getHfDownloadUrl, + getStrategy, + toastWithButton, +} from '../utils' +import { convertToGGML, convertToSt } from '../utils/convert-model' +import { ToolTipButton } from './ToolTipButton' const mainButtonText = { [ModelStatus.Offline]: 'Run', [ModelStatus.Starting]: 'Starting', [ModelStatus.Loading]: 'Loading', - [ModelStatus.Working]: 'Stop' -}; + [ModelStatus.Working]: 'Stop', +} const iconModeButtonIcon: { [modelStatus: number]: ReactElement } = { [ModelStatus.Offline]: , [ModelStatus.Starting]: , [ModelStatus.Loading]: , - [ModelStatus.Working]: -}; + [ModelStatus.Working]: , +} -export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean }> - = observer(({ - onClickRun, - iconMode -}) => { - const { t } = useTranslation(); - const navigate = useNavigate(); +export const RunButton: FC<{ + onClickRun?: MouseEventHandler + iconMode?: boolean +}> = observer(({ onClickRun, iconMode }) => { + const { t } = useTranslation() + const navigate = useNavigate() const onClickMainButton = async () => { if (commonStore.status.status === ModelStatus.Offline) { - commonStore.setStatus({ status: ModelStatus.Starting }); + commonStore.setStatus({ status: ModelStatus.Starting }) - const modelConfig = commonStore.getCurrentModelConfig(); - const webgpu = modelConfig.modelParameters.device === 'WebGPU'; - const webgpuPython = modelConfig.modelParameters.device === 'WebGPU (Python)'; - const cpp = modelConfig.modelParameters.device === 'CPU (rwkv.cpp)'; - let modelName = ''; - let modelPath = ''; + const modelConfig = commonStore.getCurrentModelConfig() + const webgpu = modelConfig.modelParameters.device === 'WebGPU' + const webgpuPython = + modelConfig.modelParameters.device === 'WebGPU (Python)' + const cpp = modelConfig.modelParameters.device === 'CPU (rwkv.cpp)' + let modelName = '' + let modelPath = '' if (modelConfig && modelConfig.modelParameters) { - modelName = modelConfig.modelParameters.modelName; - modelPath = `${commonStore.settings.customModelsPath}/${modelName}`; + modelName = modelConfig.modelParameters.modelName + modelPath = `${commonStore.settings.customModelsPath}/${modelName}` } else { - toast(t('Model Config Exception'), { type: 'error' }); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + toast(t('Model Config Exception'), { type: 'error' }) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } - const currentModelSource = commonStore.modelSourceList.find(item => item.name === modelName); + const currentModelSource = commonStore.modelSourceList.find( + (item) => item.name === modelName + ) const showDownloadPrompt = (promptInfo: string, downloadName: string) => { toastWithButton(promptInfo, t('Download'), () => { - const downloadUrl = currentModelSource?.downloadUrl; + const downloadUrl = currentModelSource?.downloadUrl if (downloadUrl) { - toastWithButton(`${t('Downloading')} ${downloadName}`, t('Check'), () => { - navigate({ pathname: '/downloads' }); + toastWithButton( + `${t('Downloading')} ${downloadName}`, + t('Check'), + () => { + navigate({ pathname: '/downloads' }) }, - { autoClose: 3000 }); - AddToDownloadList(modelPath, getHfDownloadUrl(downloadUrl)); + { autoClose: 3000 } + ) + AddToDownloadList(modelPath, getHfDownloadUrl(downloadUrl)) } else { - toast(t('Can not find download url'), { type: 'error' }); + toast(t('Can not find download url'), { type: 'error' }) } - }); - }; + }) + } if (webgpu || webgpuPython) { - if (!['.st', '.safetensors'].some(ext => modelPath.endsWith(ext))) { - const stModelPath = modelPath.replace(/\.pth$/, '.st'); + if (!['.st', '.safetensors'].some((ext) => modelPath.endsWith(ext))) { + const stModelPath = modelPath.replace(/\.pth$/, '.st') if (await FileExists(stModelPath)) { - modelPath = stModelPath; - } else if (!await FileExists(modelPath)) { - showDownloadPrompt(t('Model file not found'), modelName); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + modelPath = stModelPath + } else if (!(await FileExists(modelPath))) { + showDownloadPrompt(t('Model file not found'), modelName) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } else if (!currentModelSource?.isComplete) { - showDownloadPrompt(t('Model file download is not complete'), modelName); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + showDownloadPrompt( + t('Model file download is not complete'), + modelName + ) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } else { - toastWithButton(t('Please convert model to safe tensors format first'), t('Convert'), () => { - convertToSt(modelConfig, navigate); - }); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + toastWithButton( + t('Please convert model to safe tensors format first'), + t('Convert'), + () => { + convertToSt(modelConfig, navigate) + } + ) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } } } if (!webgpu && !webgpuPython) { - if (['.st', '.safetensors'].some(ext => modelPath.endsWith(ext))) { - toast(t('Please change Strategy to WebGPU to use safetensors format'), { type: 'error' }); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + if (['.st', '.safetensors'].some((ext) => modelPath.endsWith(ext))) { + toast( + t('Please change Strategy to WebGPU to use safetensors format'), + { type: 'error' } + ) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } } if (!webgpu) { - const ok = await checkDependencies(navigate); - if (!ok) - return; + const ok = await checkDependencies(navigate) + if (!ok) return } if (cpp) { - if (!['.bin'].some(ext => modelPath.endsWith(ext))) { - const precision: Precision = modelConfig.modelParameters.precision === 'Q5_1' ? 'Q5_1' : 'fp16'; - const ggmlModelPath = modelPath.replace(/\.pth$/, `-${precision}.bin`); + if (!['.bin'].some((ext) => modelPath.endsWith(ext))) { + const precision: Precision = + modelConfig.modelParameters.precision === 'Q5_1' ? 'Q5_1' : 'fp16' + const ggmlModelPath = modelPath.replace(/\.pth$/, `-${precision}.bin`) if (await FileExists(ggmlModelPath)) { - modelPath = ggmlModelPath; - } else if (!await FileExists(modelPath)) { - showDownloadPrompt(t('Model file not found'), modelName); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + modelPath = ggmlModelPath + } else if (!(await FileExists(modelPath))) { + showDownloadPrompt(t('Model file not found'), modelName) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } else if (!currentModelSource?.isComplete) { - showDownloadPrompt(t('Model file download is not complete'), modelName); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + showDownloadPrompt( + t('Model file download is not complete'), + modelName + ) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } else { - toastWithButton(t('Please convert model to GGML format first'), t('Convert'), () => { - convertToGGML(modelConfig, navigate); - }); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + toastWithButton( + t('Please convert model to GGML format first'), + t('Convert'), + () => { + convertToGGML(modelConfig, navigate) + } + ) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } } } if (!cpp) { - if (['.bin'].some(ext => modelPath.endsWith(ext))) { - toast(t('Please change Strategy to CPU (rwkv.cpp) to use ggml format'), { type: 'error' }); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + if (['.bin'].some((ext) => modelPath.endsWith(ext))) { + toast( + t('Please change Strategy to CPU (rwkv.cpp) to use ggml format'), + { type: 'error' } + ) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } } - if (!await FileExists(modelPath)) { - showDownloadPrompt(t('Model file not found'), modelName); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; - } else // If the user selects the .pth model with WebGPU mode, modelPath will be set to the .st model. - // However, if the .pth model is deleted, modelPath will exist and isComplete will be false. - if (!currentModelSource?.isComplete && modelPath.endsWith('.pth')) { - showDownloadPrompt(t('Model file download is not complete'), modelName); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + if (!(await FileExists(modelPath))) { + showDownloadPrompt(t('Model file not found'), modelName) + commonStore.setStatus({ status: ModelStatus.Offline }) + return + } // If the user selects the .pth model with WebGPU mode, modelPath will be set to the .st model. + // However, if the .pth model is deleted, modelPath will exist and isComplete will be false. + else if (!currentModelSource?.isComplete && modelPath.endsWith('.pth')) { + showDownloadPrompt(t('Model file download is not complete'), modelName) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } - const port = modelConfig.apiParameters.apiPort; + const port = modelConfig.apiParameters.apiPort - if (!await IsPortAvailable(port)) { - await exit(1000).catch(() => { - }); - if (!await IsPortAvailable(port)) { - toast(t('Port is occupied. Change it in Configs page or close the program that occupies the port.'), { type: 'error' }); - commonStore.setStatus({ status: ModelStatus.Offline }); - return; + if (!(await IsPortAvailable(port))) { + await exit(1000).catch(() => {}) + if (!(await IsPortAvailable(port))) { + toast( + t( + 'Port is occupied. Change it in Configs page or close the program that occupies the port.' + ), + { type: 'error' } + ) + commonStore.setStatus({ status: ModelStatus.Offline }) + return } } - const startServer = webgpu ? - (_: string, port: number, host: string) => StartWebGPUServer(port, host) - : StartServer; - const isUsingCudaBeta = modelConfig.modelParameters.device === 'CUDA-Beta'; + const startServer = webgpu + ? (_: string, port: number, host: string) => + StartWebGPUServer(port, host) + : StartServer + const isUsingCudaBeta = modelConfig.modelParameters.device === 'CUDA-Beta' - startServer(commonStore.settings.customPythonPath, port, commonStore.settings.host !== '127.0.0.1' ? '0.0.0.0' : '127.0.0.1', - !!modelConfig.enableWebUI, isUsingCudaBeta, cpp, webgpuPython + startServer( + commonStore.settings.customPythonPath, + port, + commonStore.settings.host !== '127.0.0.1' ? '0.0.0.0' : '127.0.0.1', + !!modelConfig.enableWebUI, + isUsingCudaBeta, + cpp, + webgpuPython ).catch((e) => { - const errMsg = e.message || e; + const errMsg = e.message || e if (errMsg.includes('path contains space')) - toast(`${t('Error')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' }); - else - toast(t('Error') + ' - ' + errMsg, { type: 'error' }); - }); - setTimeout(WindowShow, 1000); - setTimeout(WindowShow, 2000); - setTimeout(WindowShow, 3000); + toast(`${t('Error')} - ${t('File Path Cannot Contain Space')}`, { + type: 'error', + }) + else toast(t('Error') + ' - ' + errMsg, { type: 'error' }) + }) + setTimeout(WindowShow, 1000) + setTimeout(WindowShow, 2000) + setTimeout(WindowShow, 3000) - let timeoutCount = 6; - let loading = false; + let timeoutCount = 6 + let loading = false const intervalId = setInterval(() => { readRoot() - .then(async r => { - if (r.ok && !loading) { - loading = true; - clearInterval(intervalId); - if (!webgpu) { - await getStatus().then(status => { - if (status) - commonStore.setStatus(status); - }); - } - commonStore.setStatus({ status: ModelStatus.Loading }); - const loadingId = toast(t('Loading Model'), { type: 'info', autoClose: false }); - if (!webgpu) { - updateConfig(t, { - max_tokens: modelConfig.apiParameters.maxResponseToken, - temperature: modelConfig.apiParameters.temperature, - top_p: modelConfig.apiParameters.topP, - presence_penalty: modelConfig.apiParameters.presencePenalty, - frequency_penalty: modelConfig.apiParameters.frequencyPenalty, - penalty_decay: modelConfig.apiParameters.penaltyDecay, - global_penalty: modelConfig.apiParameters.globalPenalty, - state: modelConfig.apiParameters.stateModel - }).then(async r => { - if (r.status !== 200) { - const error = await r.text(); - if (error.includes('state shape mismatch')) - toast(t('State model mismatch'), { type: 'error' }); - else if (error.includes('file format of the model or state model not supported')) - toast(t('File format of the model or state model not supported'), { type: 'error' }); - else - toast(error, { type: 'error' }); - } - }); - } - - const strategy = getStrategy(modelConfig); - let customCudaFile = ''; - if ((modelConfig.modelParameters.device.startsWith('CUDA') || modelConfig.modelParameters.device === 'Custom') - && modelConfig.modelParameters.useCustomCuda - && !strategy.split('->').some(s => ['cuda', 'fp32'].every(v => s.includes(v)))) { - if (commonStore.platform === 'windows') { - // this part is currently unused because there's no longer a need to use different kernels for different GPUs, but it might still be needed in the future - // - // customCudaFile = getSupportedCustomCudaFile(isUsingCudaBeta); - // if (customCudaFile) { - // let kernelTargetPath: string; - // if (isUsingCudaBeta) - // kernelTargetPath = './backend-python/rwkv_pip/beta/wkv_cuda.pyd'; - // else - // kernelTargetPath = './backend-python/rwkv_pip/wkv_cuda.pyd'; - // await CopyFile(customCudaFile, kernelTargetPath).catch(() => { - // FileExists(kernelTargetPath).then((exist) => { - // if (!exist) { - // customCudaFile = ''; - // toast(t('Failed to copy custom cuda file'), { type: 'error' }); - // } - // }); - // }); - // } else - // toast(t('Supported custom cuda file not found'), { type: 'warning' }); - customCudaFile = 'any'; - } else { - customCudaFile = 'any'; + .then(async (r) => { + if (r.ok && !loading) { + loading = true + clearInterval(intervalId) + if (!webgpu) { + await getStatus().then((status) => { + if (status) commonStore.setStatus(status) + }) + } + commonStore.setStatus({ status: ModelStatus.Loading }) + const loadingId = toast(t('Loading Model'), { + type: 'info', + autoClose: false, + }) + if (!webgpu) { + updateConfig(t, { + max_tokens: modelConfig.apiParameters.maxResponseToken, + temperature: modelConfig.apiParameters.temperature, + top_p: modelConfig.apiParameters.topP, + presence_penalty: modelConfig.apiParameters.presencePenalty, + frequency_penalty: modelConfig.apiParameters.frequencyPenalty, + penalty_decay: modelConfig.apiParameters.penaltyDecay, + global_penalty: modelConfig.apiParameters.globalPenalty, + state: modelConfig.apiParameters.stateModel, + }).then(async (r) => { + if (r.status !== 200) { + const error = await r.text() + if (error.includes('state shape mismatch')) + toast(t('State model mismatch'), { type: 'error' }) + else if ( + error.includes( + 'file format of the model or state model not supported' + ) + ) + toast( + t( + 'File format of the model or state model not supported' + ), + { type: 'error' } + ) + else toast(error, { type: 'error' }) + } + }) } - } - switchModel({ - model: modelPath, - strategy: strategy, - tokenizer: modelConfig.modelParameters.useCustomTokenizer ? modelConfig.modelParameters.customTokenizer : undefined, - customCuda: customCudaFile !== '', - deploy: modelConfig.enableWebUI - }).then(async (r) => { - if (r.ok) { - commonStore.setStatus({ status: ModelStatus.Working }); - let buttonNameMap = { - 'novel': 'Completion', - 'abc': 'Composition', - 'midi': 'Composition' - }; - let buttonName = 'Chat'; - buttonName = Object.entries(buttonNameMap).find(([key, value]) => modelName.toLowerCase().includes(key))?.[1] || buttonName; - const buttonFn = () => { - navigate({ pathname: '/' + buttonName.toLowerCase() }); - }; - if (modelName.toLowerCase().includes('abc') && commonStore.compositionParams.prompt === defaultCompositionPrompt) { - commonStore.setCompositionParams({ - ...commonStore.compositionParams, - prompt: defaultCompositionABCPrompt - }); - commonStore.setCompositionSubmittedPrompt(defaultCompositionABCPrompt); + const strategy = getStrategy(modelConfig) + let customCudaFile = '' + if ( + (modelConfig.modelParameters.device.startsWith('CUDA') || + modelConfig.modelParameters.device === 'Custom') && + modelConfig.modelParameters.useCustomCuda && + !strategy + .split('->') + .some((s) => ['cuda', 'fp32'].every((v) => s.includes(v))) + ) { + if (commonStore.platform === 'windows') { + // this part is currently unused because there's no longer a need to use different kernels for different GPUs, but it might still be needed in the future + // + // customCudaFile = getSupportedCustomCudaFile(isUsingCudaBeta); + // if (customCudaFile) { + // let kernelTargetPath: string; + // if (isUsingCudaBeta) + // kernelTargetPath = './backend-python/rwkv_pip/beta/wkv_cuda.pyd'; + // else + // kernelTargetPath = './backend-python/rwkv_pip/wkv_cuda.pyd'; + // await CopyFile(customCudaFile, kernelTargetPath).catch(() => { + // FileExists(kernelTargetPath).then((exist) => { + // if (!exist) { + // customCudaFile = ''; + // toast(t('Failed to copy custom cuda file'), { type: 'error' }); + // } + // }); + // }); + // } else + // toast(t('Supported custom cuda file not found'), { type: 'warning' }); + customCudaFile = 'any' + } else { + customCudaFile = 'any' } - - if (modelConfig.modelParameters.device.startsWith('CUDA') && - modelConfig.modelParameters.storedLayers < modelConfig.modelParameters.maxStoredLayers && - commonStore.monitorData && commonStore.monitorData.totalVram !== 0 && - (commonStore.monitorData.usedVram / commonStore.monitorData.totalVram) < 0.9) - toast(t('You can increase the number of stored layers in Configs page to improve performance'), { type: 'info' }); - toastWithButton(t('Startup Completed'), t(buttonName), buttonFn, { type: 'success', autoClose: 3000 }); - } else if (r.status === 304) { - toast(t('Loading Model'), { type: 'info' }); - } else { - commonStore.setStatus({ status: ModelStatus.Offline }); - const error = await r.text(); - const errorsMap = { - 'not enough memory': 'Memory is not enough, try to increase the virtual memory or use a smaller model.', - 'not compiled with CUDA': 'Bad PyTorch version, please reinstall PyTorch with cuda.', - 'invalid header or archive is corrupted': 'The model file is corrupted, please download again.', - 'no NVIDIA driver': 'Found no NVIDIA driver, please install the latest driver. If you are not using an Nvidia GPU, please switch the \'Strategy\' to WebGPU or CPU in the Configs page.', - 'CUDA out of memory': 'VRAM is not enough, please reduce stored layers or use a lower precision in Configs page.', - 'Ninja is required to load C++ extensions': 'Failed to enable custom CUDA kernel, ninja is required to load C++ extensions. You may be using the CPU version of PyTorch, please reinstall PyTorch with CUDA. Or if you are using a custom Python interpreter, you must compile the CUDA kernel by yourself or disable Custom CUDA kernel acceleration.', - 're-convert the model': 'Model has been converted and does not match current strategy. If you are using a new strategy, re-convert the model.' - }; - const matchedError = Object.entries(errorsMap).find(([key, _]) => error.includes(key)); - const message = matchedError ? t(matchedError[1]) : error; - toast(t('Failed to switch model') + ' - ' + message, { autoClose: 5000, type: 'error' }); } - }).catch((e) => { - commonStore.setStatus({ status: ModelStatus.Offline }); - toast(t('Failed to switch model') + ' - ' + (e.message || e), { type: 'error' }); - }).finally(() => { - toast.dismiss(loadingId); - }); - } - }).catch(() => { - if (timeoutCount <= 0) { - clearInterval(intervalId); - commonStore.setStatus({ status: ModelStatus.Offline }); - } - }); - timeoutCount--; - }, 1000); + switchModel({ + model: modelPath, + strategy: strategy, + tokenizer: modelConfig.modelParameters.useCustomTokenizer + ? modelConfig.modelParameters.customTokenizer + : undefined, + customCuda: customCudaFile !== '', + deploy: modelConfig.enableWebUI, + }) + .then(async (r) => { + if (r.ok) { + commonStore.setStatus({ status: ModelStatus.Working }) + let buttonNameMap = { + novel: 'Completion', + abc: 'Composition', + midi: 'Composition', + } + let buttonName = 'Chat' + buttonName = + Object.entries(buttonNameMap).find(([key, value]) => + modelName.toLowerCase().includes(key) + )?.[1] || buttonName + const buttonFn = () => { + navigate({ pathname: '/' + buttonName.toLowerCase() }) + } + if ( + modelName.toLowerCase().includes('abc') && + commonStore.compositionParams.prompt === + defaultCompositionPrompt + ) { + commonStore.setCompositionParams({ + ...commonStore.compositionParams, + prompt: defaultCompositionABCPrompt, + }) + commonStore.setCompositionSubmittedPrompt( + defaultCompositionABCPrompt + ) + } + + if ( + modelConfig.modelParameters.device.startsWith('CUDA') && + modelConfig.modelParameters.storedLayers < + modelConfig.modelParameters.maxStoredLayers && + commonStore.monitorData && + commonStore.monitorData.totalVram !== 0 && + commonStore.monitorData.usedVram / + commonStore.monitorData.totalVram < + 0.9 + ) + toast( + t( + 'You can increase the number of stored layers in Configs page to improve performance' + ), + { type: 'info' } + ) + toastWithButton( + t('Startup Completed'), + t(buttonName), + buttonFn, + { type: 'success', autoClose: 3000 } + ) + } else if (r.status === 304) { + toast(t('Loading Model'), { type: 'info' }) + } else { + commonStore.setStatus({ status: ModelStatus.Offline }) + const error = await r.text() + const errorsMap = { + 'not enough memory': + 'Memory is not enough, try to increase the virtual memory or use a smaller model.', + 'not compiled with CUDA': + 'Bad PyTorch version, please reinstall PyTorch with cuda.', + 'invalid header or archive is corrupted': + 'The model file is corrupted, please download again.', + 'no NVIDIA driver': + "Found no NVIDIA driver, please install the latest driver. If you are not using an Nvidia GPU, please switch the 'Strategy' to WebGPU or CPU in the Configs page.", + 'CUDA out of memory': + 'VRAM is not enough, please reduce stored layers or use a lower precision in Configs page.', + 'Ninja is required to load C++ extensions': + 'Failed to enable custom CUDA kernel, ninja is required to load C++ extensions. You may be using the CPU version of PyTorch, please reinstall PyTorch with CUDA. Or if you are using a custom Python interpreter, you must compile the CUDA kernel by yourself or disable Custom CUDA kernel acceleration.', + 're-convert the model': + 'Model has been converted and does not match current strategy. If you are using a new strategy, re-convert the model.', + } + const matchedError = Object.entries(errorsMap).find( + ([key, _]) => error.includes(key) + ) + const message = matchedError ? t(matchedError[1]) : error + toast(t('Failed to switch model') + ' - ' + message, { + autoClose: 5000, + type: 'error', + }) + } + }) + .catch((e) => { + commonStore.setStatus({ status: ModelStatus.Offline }) + toast( + t('Failed to switch model') + ' - ' + (e.message || e), + { type: 'error' } + ) + }) + .finally(() => { + toast.dismiss(loadingId) + }) + } + }) + .catch(() => { + if (timeoutCount <= 0) { + clearInterval(intervalId) + commonStore.setStatus({ status: ModelStatus.Offline }) + } + }) + + timeoutCount-- + }, 1000) } else { - commonStore.setStatus({ status: ModelStatus.Offline }); - exit().then(r => { + commonStore.setStatus({ status: ModelStatus.Offline }) + exit().then((r) => { if (r.status === 403) if (commonStore.platform !== 'linux') - toast(t('Server is working on deployment mode, please close the terminal window manually'), { type: 'info' }); + toast( + t( + 'Server is working on deployment mode, please close the terminal window manually' + ), + { type: 'info' } + ) else - toast(t('Server is working on deployment mode, please exit the program manually to stop the server'), { type: 'info' }); - }); + toast( + t( + 'Server is working on deployment mode, please exit the program manually to stop the server' + ), + { type: 'info' } + ) + }) } - }; + } const onClick = async (e: any) => { - if (commonStore.status.status === ModelStatus.Offline) - await onClickRun?.(e); - await onClickMainButton(); - }; + if (commonStore.status.status === ModelStatus.Offline) await onClickRun?.(e) + await onClickMainButton() + } - return (iconMode ? - - : - - ); -}); + return iconMode ? ( + + ) : ( + + ) +}) diff --git a/frontend/src/components/Section.tsx b/frontend/src/components/Section.tsx index 643c2986..ebb69cb7 100644 --- a/frontend/src/components/Section.tsx +++ b/frontend/src/components/Section.tsx @@ -1,21 +1,21 @@ -import { FC, ReactElement } from 'react'; -import { Card, Text } from '@fluentui/react-components'; +import { FC, ReactElement } from 'react' +import { Card, Text } from '@fluentui/react-components' export const Section: FC<{ - title: string; desc?: string | null, content: ReactElement, outline?: boolean -}> = - ({ title, desc, content, outline = true }) => { - return ( - -
-
- {title} - {desc && {desc}} -
+ title: string + desc?: string | null + content: ReactElement + outline?: boolean +}> = ({ title, desc, content, outline = true }) => { + return ( + +
+
+ {title} + {desc && {desc}}
-
- {content} -
- - ); - }; +
+
{content}
+
+ ) +} diff --git a/frontend/src/components/ToolTipButton.tsx b/frontend/src/components/ToolTipButton.tsx index 4c774883..a0ac58cb 100644 --- a/frontend/src/components/ToolTipButton.tsx +++ b/frontend/src/components/ToolTipButton.tsx @@ -1,18 +1,23 @@ -import React, { CSSProperties, FC, MouseEventHandler, ReactElement } from 'react'; -import { Button, Tooltip } from '@fluentui/react-components'; +import React, { + CSSProperties, + FC, + MouseEventHandler, + ReactElement, +} from 'react' +import { Button, Tooltip } from '@fluentui/react-components' export const ToolTipButton: FC<{ - text?: string | null, - desc: string, - icon?: ReactElement, - className?: string, - style?: CSSProperties, - size?: 'small' | 'medium' | 'large', - shape?: 'rounded' | 'circular' | 'square'; - appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent'; - disabled?: boolean, + text?: string | null + desc: string + icon?: ReactElement + className?: string + style?: CSSProperties + size?: 'small' | 'medium' | 'large' + shape?: 'rounded' | 'circular' | 'square' + appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent' + disabled?: boolean onClick?: MouseEventHandler - showDelay?: number, + showDelay?: number }> = ({ text, desc, @@ -24,14 +29,40 @@ export const ToolTipButton: FC<{ appearance, disabled, onClick, - showDelay = 0 + showDelay = 0, }) => { - return (desc ? - - - : - - ); -}; + return desc ? ( + + + + ) : ( + + ) +} diff --git a/frontend/src/components/ValuedSlider.tsx b/frontend/src/components/ValuedSlider.tsx index a60cb2e7..5cc2f948 100644 --- a/frontend/src/components/ValuedSlider.tsx +++ b/frontend/src/components/ValuedSlider.tsx @@ -1,35 +1,58 @@ -import React, { FC, useEffect, useRef } from 'react'; -import { Slider, Text } from '@fluentui/react-components'; -import { SliderOnChangeData } from '@fluentui/react-slider'; -import { NumberInput } from './NumberInput'; +import React, { FC, useEffect, useRef } from 'react' +import { Slider, Text } from '@fluentui/react-components' +import { SliderOnChangeData } from '@fluentui/react-slider' +import { NumberInput } from './NumberInput' export const ValuedSlider: FC<{ - value: number, - min: number, - max: number, - step?: number, + value: number + min: number + max: number + step?: number input?: boolean - onChange?: (ev: React.ChangeEvent, data: SliderOnChangeData) => void, + onChange?: ( + ev: React.ChangeEvent, + data: SliderOnChangeData + ) => void toFixed?: number disabled?: boolean }> = ({ value, min, max, step, input, onChange, toFixed, disabled }) => { - const sliderRef = useRef(null); + const sliderRef = useRef(null) useEffect(() => { if (step && sliderRef.current && sliderRef.current.parentElement) { if ((max - min) / step > 10) - sliderRef.current.parentElement.style.removeProperty('--fui-Slider--steps-percent'); + sliderRef.current.parentElement.style.removeProperty( + '--fui-Slider--steps-percent' + ) } - }, []); + }, []) return (
- - {input - ? - : {value}} + + {input ? ( + + ) : ( + {value} + )}
- ); -}; + ) +} diff --git a/frontend/src/components/WorkHeader.tsx b/frontend/src/components/WorkHeader.tsx index 1f3bc955..52226e8c 100644 --- a/frontend/src/components/WorkHeader.tsx +++ b/frontend/src/components/WorkHeader.tsx @@ -1,53 +1,61 @@ -import React, { FC } from 'react'; -import { observer } from 'mobx-react-lite'; -import { Divider, PresenceBadge, Text } from '@fluentui/react-components'; -import commonStore, { ModelStatus } from '../stores/commonStore'; -import { ConfigSelector } from './ConfigSelector'; -import { RunButton } from './RunButton'; -import { PresenceBadgeStatus } from '@fluentui/react-badge'; -import { useTranslation } from 'react-i18next'; -import { useMediaQuery } from 'usehooks-ts'; +import React, { FC } from 'react' +import { PresenceBadgeStatus } from '@fluentui/react-badge' +import { Divider, PresenceBadge, Text } from '@fluentui/react-components' +import { observer } from 'mobx-react-lite' +import { useTranslation } from 'react-i18next' +import { useMediaQuery } from 'usehooks-ts' +import commonStore, { ModelStatus } from '../stores/commonStore' +import { ConfigSelector } from './ConfigSelector' +import { RunButton } from './RunButton' const statusText = { [ModelStatus.Offline]: 'Offline', [ModelStatus.Starting]: 'Starting', [ModelStatus.Loading]: 'Loading', - [ModelStatus.Working]: 'Working' -}; + [ModelStatus.Working]: 'Working', +} const badgeStatus: { [modelStatus: number]: PresenceBadgeStatus } = { [ModelStatus.Offline]: 'unknown', [ModelStatus.Starting]: 'away', [ModelStatus.Loading]: 'away', - [ModelStatus.Working]: 'available' -}; + [ModelStatus.Working]: 'available', +} export const WorkHeader: FC = observer(() => { - const { t } = useTranslation(); - const mq = useMediaQuery('(min-width: 640px)'); - const port = commonStore.getCurrentModelConfig().apiParameters.apiPort; + const { t } = useTranslation() + const mq = useMediaQuery('(min-width: 640px)') + const port = commonStore.getCurrentModelConfig().apiParameters.apiPort - return commonStore.platform === 'web' ? -
: + return commonStore.platform === 'web' ? ( +
+ ) : (
-
+
- {t('Model Status') + ': ' + t(statusText[commonStore.status.status])} -
- {commonStore.lastModelName && mq && - {commonStore.lastModelName} - } + {t('Model Status') + + ': ' + + t(statusText[commonStore.status.status])} + +
+ {commonStore.lastModelName && mq && ( + {commonStore.lastModelName} + )}
- {t('This tool\'s API is compatible with OpenAI API. It can be used with any ChatGPT tool you like. Go to the settings of some ChatGPT tool, replace the \'https://api.openai.com\' part in the API address with \'') + `http://127.0.0.1:${port}` + '\'.'} + {t( + "This tool's API is compatible with OpenAI API. It can be used with any ChatGPT tool you like. Go to the settings of some ChatGPT tool, replace the 'https://api.openai.com' part in the API address with '" + ) + + `http://127.0.0.1:${port}` + + "'."}
- ; -}); \ No newline at end of file + ) +}) diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index bbf8af84..3db56a94 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -1,25 +1,25 @@ -import './webWails'; -import React from 'react'; -import { createRoot } from 'react-dom/client'; -import './style.scss'; -import 'react-toastify/dist/ReactToastify.css'; -import App from './App'; -import { HashRouter } from 'react-router-dom'; -import { startup } from './startup'; -import './_locales/i18n-react'; -import { WindowShow } from '../wailsjs/runtime'; +import './webWails' +import React from 'react' +import { createRoot } from 'react-dom/client' +import './style.scss' +import 'react-toastify/dist/ReactToastify.css' +import { HashRouter } from 'react-router-dom' +import App from './App' +import { startup } from './startup' +import './_locales/i18n-react' +import { WindowShow } from '../wailsjs/runtime' startup().then(() => { - const container = document.getElementById('root'); + const container = document.getElementById('root') - const root = createRoot(container!); + const root = createRoot(container!) root.render( - ); + ) // force display the window - WindowShow(); -}); + WindowShow() +}) diff --git a/frontend/src/pages/About.tsx b/frontend/src/pages/About.tsx index 608dab8f..3e4814d2 100644 --- a/frontend/src/pages/About.tsx +++ b/frontend/src/pages/About.tsx @@ -1,23 +1,28 @@ -import React, { FC } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Page } from '../components/Page'; -import MarkdownRender from '../components/MarkdownRender'; -import { observer } from 'mobx-react-lite'; -import commonStore from '../stores/commonStore'; +import React, { FC } from 'react' +import { observer } from 'mobx-react-lite' +import { useTranslation } from 'react-i18next' +import MarkdownRender from '../components/MarkdownRender' +import { Page } from '../components/Page' +import commonStore from '../stores/commonStore' const About: FC = observer(() => { - const { t } = useTranslation(); - const lang: string = commonStore.settings.language; + const { t } = useTranslation() + const lang: string = commonStore.settings.language return ( - - - {lang in commonStore.about ? commonStore.about[lang] : commonStore.about['en']} - -
- } /> - ); -}); + + + {lang in commonStore.about + ? commonStore.about[lang] + : commonStore.about['en']} + +
+ } + /> + ) +}) -export default About; +export default About diff --git a/frontend/src/pages/AudiotrackManager/AudiotrackButton.tsx b/frontend/src/pages/AudiotrackManager/AudiotrackButton.tsx index 07a49abb..909f8a7c 100644 --- a/frontend/src/pages/AudiotrackManager/AudiotrackButton.tsx +++ b/frontend/src/pages/AudiotrackManager/AudiotrackButton.tsx @@ -1,40 +1,61 @@ -import React, { FC, lazy } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Button, Dialog, DialogBody, DialogContent, DialogSurface, DialogTrigger } from '@fluentui/react-components'; -import { CustomToastContainer } from '../../components/CustomToastContainer'; -import { LazyImportComponent } from '../../components/LazyImportComponent'; -import { flushMidiRecordingContent } from '../../utils'; -import commonStore from '../../stores/commonStore'; +import React, { FC, lazy } from 'react' +import { + Button, + Dialog, + DialogBody, + DialogContent, + DialogSurface, + DialogTrigger, +} from '@fluentui/react-components' +import { useTranslation } from 'react-i18next' +import { CustomToastContainer } from '../../components/CustomToastContainer' +import { LazyImportComponent } from '../../components/LazyImportComponent' +import commonStore from '../../stores/commonStore' +import { flushMidiRecordingContent } from '../../utils' -const AudiotrackEditor = lazy(() => import('./AudiotrackEditor')); +const AudiotrackEditor = lazy(() => import('./AudiotrackEditor')) export const AudiotrackButton: FC<{ - size?: 'small' | 'medium' | 'large', - shape?: 'rounded' | 'circular' | 'square'; - appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent'; - setPrompt: (prompt: string) => void; + size?: 'small' | 'medium' | 'large' + shape?: 'rounded' | 'circular' | 'square' + appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent' + setPrompt: (prompt: string) => void }> = ({ size, shape, appearance, setPrompt }) => { - const { t } = useTranslation(); + const { t } = useTranslation() - return { - if (!data.open) { - flushMidiRecordingContent(); - commonStore.setRecordingTrackId(''); - commonStore.setPlayingTrackId(''); - } - }}> - - - - - - - - - - - - ; -}; \ No newline at end of file + return ( + { + if (!data.open) { + flushMidiRecordingContent() + commonStore.setRecordingTrackId('') + commonStore.setPlayingTrackId('') + } + }} + > + + + + + + + + + + + + + ) +} diff --git a/frontend/src/pages/AudiotrackManager/AudiotrackEditor.tsx b/frontend/src/pages/AudiotrackManager/AudiotrackEditor.tsx index d77d3faa..ed2e836f 100644 --- a/frontend/src/pages/AudiotrackManager/AudiotrackEditor.tsx +++ b/frontend/src/pages/AudiotrackManager/AudiotrackEditor.tsx @@ -1,9 +1,12 @@ -import React, { FC, useEffect, useRef, useState } from 'react'; -import { observer } from 'mobx-react-lite'; -import { useTranslation } from 'react-i18next'; -import Draggable from 'react-draggable'; -import { ToolTipButton } from '../../components/ToolTipButton'; -import { v4 as uuid } from 'uuid'; +import React, { FC, useEffect, useRef, useState } from 'react' +import { + Button, + Card, + DialogTrigger, + Slider, + Text, + Tooltip, +} from '@fluentui/react-components' import { Add16Regular, ArrowAutofitWidth20Regular, @@ -14,59 +17,76 @@ import { Play16Filled, Play16Regular, Record16Regular, - Stop16Filled -} from '@fluentui/react-icons'; -import { Button, Card, DialogTrigger, Slider, Text, Tooltip } from '@fluentui/react-components'; -import { useWindowSize } from 'usehooks-ts'; -import commonStore, { ModelStatus } from '../../stores/commonStore'; -import classnames from 'classnames'; + Stop16Filled, +} from '@fluentui/react-icons' +import classnames from 'classnames' +import { observer } from 'mobx-react-lite' +import Draggable from 'react-draggable' +import { useTranslation } from 'react-i18next' +import { toast } from 'react-toastify' +import { useWindowSize } from 'usehooks-ts' +import { v4 as uuid } from 'uuid' +import { PlayNote } from '../../../wailsjs/go/backend_golang/App' +import { ToolTipButton } from '../../components/ToolTipButton' +import commonStore, { ModelStatus } from '../../stores/commonStore' import { InstrumentType, InstrumentTypeNameMap, InstrumentTypeTokenMap, MidiMessage, - tracksMinimalTotalTime -} from '../../types/composition'; -import { toast } from 'react-toastify'; + tracksMinimalTotalTime, +} from '../../types/composition' import { flushMidiRecordingContent, getMidiRawContentMainInstrument, getMidiRawContentTime, getReqUrl, OpenFileDialog, - refreshTracksTotalTime -} from '../../utils'; -import { PlayNote } from '../../../wailsjs/go/backend_golang/App'; - -const snapValue = 25; -const minimalMoveTime = 8; // 1000/125=8ms wait_events=125 -const scaleMin = 0.05; -const scaleMax = 3; -const baseMoveTime = Math.round(minimalMoveTime / scaleMin); - -const velocityEvents = 128; -const velocityBins = 12; -const velocityExp = 0.5; - -const minimalTrackWidth = 80; -const trackInitOffsetPx = 10; -const pixelFix = 0.5; -const topToArrowIcon = 19; -const arrowIconToTracks = 23; + refreshTracksTotalTime, +} from '../../utils' + +const snapValue = 25 +const minimalMoveTime = 8 // 1000/125=8ms wait_events=125 +const scaleMin = 0.05 +const scaleMax = 3 +const baseMoveTime = Math.round(minimalMoveTime / scaleMin) + +const velocityEvents = 128 +const velocityBins = 12 +const velocityExp = 0.5 + +const minimalTrackWidth = 80 +const trackInitOffsetPx = 10 +const pixelFix = 0.5 +const topToArrowIcon = 19 +const arrowIconToTracks = 23 const velocityToBin = (velocity: number) => { - velocity = Math.max(0, Math.min(velocity, velocityEvents - 1)); - const binsize = velocityEvents / (velocityBins - 1); - return Math.ceil((velocityEvents * ((Math.pow(velocityExp, (velocity / velocityEvents)) - 1.0) / (velocityExp - 1.0))) / binsize); -}; + velocity = Math.max(0, Math.min(velocity, velocityEvents - 1)) + const binsize = velocityEvents / (velocityBins - 1) + return Math.ceil( + (velocityEvents * + ((Math.pow(velocityExp, velocity / velocityEvents) - 1.0) / + (velocityExp - 1.0))) / + binsize + ) +} const binToVelocity = (bin: number) => { - const binsize = velocityEvents / (velocityBins - 1); - return Math.max(0, Math.ceil(velocityEvents * (Math.log(((velocityExp - 1) * binsize * bin) / velocityEvents + 1) / Math.log(velocityExp)) - 1)); -}; + const binsize = velocityEvents / (velocityBins - 1) + return Math.max( + 0, + Math.ceil( + velocityEvents * + (Math.log(((velocityExp - 1) * binsize * bin) / velocityEvents + 1) / + Math.log(velocityExp)) - + 1 + ) + ) +} const tokenToMidiMessage = (token: string): MidiMessage | null => { - if (token.startsWith('<')) return null; + if (token.startsWith('<')) return null if (token.startsWith('t') && !token.startsWith('t:')) { return { messageType: 'ElapsedTime', @@ -75,25 +95,28 @@ const tokenToMidiMessage = (token: string): MidiMessage | null => { note: 0, velocity: 0, control: 0, - instrument: 0 - }; + instrument: 0, + } } - const instrument: InstrumentType = InstrumentTypeTokenMap.findIndex(t => token.startsWith(t + ':')); + const instrument: InstrumentType = InstrumentTypeTokenMap.findIndex((t) => + token.startsWith(t + ':') + ) if (instrument >= 0) { - const parts = token.split(':'); - if (parts.length !== 3) return null; - const note = parseInt(parts[1], 16); - const velocity = parseInt(parts[2], 16); - if (velocity < 0 || velocity > 127) return null; - if (velocity === 0) return { - messageType: 'NoteOff', - note: note, - instrument: instrument, - channel: 0, - velocity: 0, - control: 0, - value: 0 - }; + const parts = token.split(':') + if (parts.length !== 3) return null + const note = parseInt(parts[1], 16) + const velocity = parseInt(parts[2], 16) + if (velocity < 0 || velocity > 127) return null + if (velocity === 0) + return { + messageType: 'NoteOff', + note: note, + instrument: instrument, + channel: 0, + velocity: 0, + control: 0, + value: 0, + } return { messageType: 'NoteOn', note: note, @@ -101,496 +124,729 @@ const tokenToMidiMessage = (token: string): MidiMessage | null => { instrument: instrument, channel: 0, control: 0, - value: 0 - } as MidiMessage; + value: 0, + } as MidiMessage } - return null; -}; + return null +} const midiMessageToToken = (msg: MidiMessage) => { if (msg.messageType === 'NoteOn' || msg.messageType === 'NoteOff') { - const instrument = InstrumentTypeTokenMap[msg.instrument]; - const note = msg.note.toString(16); - const velocity = velocityToBin(msg.velocity).toString(16); - return `${instrument}:${note}:${velocity} `; + const instrument = InstrumentTypeTokenMap[msg.instrument] + const note = msg.note.toString(16) + const velocity = velocityToBin(msg.velocity).toString(16) + return `${instrument}:${note}:${velocity} ` } else if (msg.messageType === 'ElapsedTime') { - let time = Math.round(msg.value / minimalMoveTime); - const num = Math.floor(time / 125); // wait_events=125 - time -= num * 125; - let ret = ''; + let time = Math.round(msg.value / minimalMoveTime) + const num = Math.floor(time / 125) // wait_events=125 + time -= num * 125 + let ret = '' for (let i = 0; i < num; i++) { - ret += 't125 '; + ret += 't125 ' } - if (time > 0) - ret += `t${time} `; - return ret; - } else - return ''; -}; + if (time > 0) ret += `t${time} ` + return ret + } else return '' +} -let dropRecordingTime = false; +let dropRecordingTime = false export const midiMessageHandler = async (data: MidiMessage) => { if (data.messageType === 'ControlChange') { - commonStore.setInstrumentType(Math.round(data.value / 127 * (InstrumentTypeNameMap.length - 1))); - return; + commonStore.setInstrumentType( + Math.round((data.value / 127) * (InstrumentTypeNameMap.length - 1)) + ) + return } if (commonStore.recordingTrackId) { if (dropRecordingTime && data.messageType === 'ElapsedTime') { - dropRecordingTime = false; - return; + dropRecordingTime = false + return } data = { ...data, - instrument: commonStore.instrumentType - }; - commonStore.setRecordingRawContent([...commonStore.recordingRawContent, data]); - commonStore.setRecordingContent(commonStore.recordingContent + midiMessageToToken(data)); + instrument: commonStore.instrumentType, + } + commonStore.setRecordingRawContent([ + ...commonStore.recordingRawContent, + data, + ]) + commonStore.setRecordingContent( + commonStore.recordingContent + midiMessageToToken(data) + ) //TODO data.channel = data.instrument; - PlayNote(data); + PlayNote(data) } -}; +} type TrackProps = { - id: string; - right: number; - scale: number; - isSelected: boolean; - onSelect: (id: string) => void; -}; - -const Track: React.FC = observer(({ - id, - right, - scale, - isSelected, - onSelect -}) => { - const { t } = useTranslation(); - const trackIndex = commonStore.tracks.findIndex(t => t.id === id)!; - const track = commonStore.tracks[trackIndex]; - const trackClass = isSelected ? 'bg-blue-600' : (commonStore.settings.darkMode ? 'bg-blue-900' : 'bg-gray-700'); - const controlX = useRef(0); - - let trackName = t('Track') + ' ' + id; - if (track.mainInstrument) - trackName = t('Track') + ' - ' + t('Piano is the main instrument')!.replace(t('Piano')!, t(track.mainInstrument)) + (track.content && (' - ' + track.content)); - else if (track.content) - trackName = t('Track') + ' - ' + track.content; - - return ( - { - controlX.current = data.lastX; - }} - onStop={(e, data) => { - const delta = data.lastX - controlX.current; - let offsetTime = Math.round(Math.round(delta / snapValue * baseMoveTime * scale) / minimalMoveTime) * minimalMoveTime; - offsetTime = Math.min(Math.max( - offsetTime, - -track.offsetTime), commonStore.trackTotalTime - track.offsetTime); - - const tracks = commonStore.tracks.slice(); - tracks[trackIndex].offsetTime += offsetTime; - commonStore.setTracks(tracks); - refreshTracksTotalTime(); - }} - > -
void +} + +const Track: React.FC = observer( + ({ id, right, scale, isSelected, onSelect }) => { + const { t } = useTranslation() + const trackIndex = commonStore.tracks.findIndex((t) => t.id === id)! + const track = commonStore.tracks[trackIndex] + const trackClass = isSelected + ? 'bg-blue-600' + : commonStore.settings.darkMode + ? 'bg-blue-900' + : 'bg-gray-700' + const controlX = useRef(0) + + let trackName = t('Track') + ' ' + id + if (track.mainInstrument) + trackName = + t('Track') + + ' - ' + + t('Piano is the main instrument')!.replace( + t('Piano')!, + t(track.mainInstrument) + ) + + (track.content && ' - ' + track.content) + else if (track.content) trackName = t('Track') + ' - ' + track.content + + return ( + { + controlX.current = data.lastX + }} + onStop={(e, data) => { + const delta = data.lastX - controlX.current + let offsetTime = + Math.round( + Math.round((delta / snapValue) * baseMoveTime * scale) / + minimalMoveTime + ) * minimalMoveTime + offsetTime = Math.min( + Math.max(offsetTime, -track.offsetTime), + commonStore.trackTotalTime - track.offsetTime + ) + + const tracks = commonStore.tracks.slice() + tracks[trackIndex].offsetTime += offsetTime + commonStore.setTracks(tracks) + refreshTracksTotalTime() }} - onClick={() => onSelect(id)} > - {trackName} -
-
- ); -}); - -const AudiotrackEditor: FC<{ setPrompt: (prompt: string) => void }> = observer(({ setPrompt }) => { - const { t } = useTranslation(); - - const viewControlsContainerRef = useRef(null); - const currentTimeControlRef = useRef(null); - const playStartTimeControlRef = useRef(null); - const tracksEndLineRef = useRef(null); - const tracksRef = useRef(null); - const toolbarRef = useRef(null); - const toolbarButtonRef = useRef(null); - const toolbarSliderRef = useRef(null); - const contentPreviewRef = useRef(null); - - const [refreshRef, setRefreshRef] = useState(false); - - const windowSize = useWindowSize(); - const scale = (scaleMin + scaleMax) - commonStore.trackScale; - - const [selectedTrackId, setSelectedTrackId] = useState(''); - const playStartTimeControlX = useRef(0); - const selectedTrack = selectedTrackId ? commonStore.tracks.find(t => t.id === selectedTrackId) : undefined; - - useEffect(() => { - if (toolbarSliderRef.current && toolbarSliderRef.current.parentElement) - toolbarSliderRef.current.parentElement.style.removeProperty('--fui-Slider--steps-percent'); - }, []); - - const scrollContentToBottom = () => { - if (contentPreviewRef.current) - contentPreviewRef.current.scrollTop = contentPreviewRef.current.scrollHeight; - }; - - useEffect(() => { - scrollContentToBottom(); - }, [commonStore.recordingContent]); - - useEffect(() => { - setRefreshRef(!refreshRef); - }, [windowSize, commonStore.tracks]); - - const viewControlsContainerWidth = (toolbarRef.current && toolbarButtonRef.current && toolbarSliderRef.current) ? - toolbarRef.current.clientWidth - toolbarButtonRef.current.clientWidth - toolbarSliderRef.current.clientWidth - 16 // 16 = ml-2 mr-2 - : 0; - const tracksWidth = viewControlsContainerWidth; - const timeOfTracksWidth = Math.floor(tracksWidth / snapValue) // number of moves - * baseMoveTime * scale; - const currentTimeControlWidth = (timeOfTracksWidth < commonStore.trackTotalTime) - ? timeOfTracksWidth / commonStore.trackTotalTime * viewControlsContainerWidth - : 0; - const playStartTimeControlPosition = (commonStore.trackPlayStartTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue; - const tracksEndPosition = (commonStore.trackTotalTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue; - const moveableTracksWidth = (tracksEndLineRef.current && viewControlsContainerRef.current && - ((tracksEndLineRef.current.getBoundingClientRect().left - (viewControlsContainerRef.current.getBoundingClientRect().left + trackInitOffsetPx)) > 0)) - ? tracksEndLineRef.current.getBoundingClientRect().left - (viewControlsContainerRef.current.getBoundingClientRect().left + trackInitOffsetPx) - : Infinity; - - return ( -
-
- {`${commonStore.trackPlayStartTime} ms / ${commonStore.trackTotalTime} ms`} -
-
-
- } /> - } onClick={() => { - commonStore.setTracks([]); - commonStore.setTrackScale(1); - commonStore.setTrackTotalTime(tracksMinimalTotalTime); - commonStore.setTrackCurrentTime(0); - commonStore.setTrackPlayStartTime(0); - }} /> +
onSelect(id)} + > + {trackName}
-
-
-
- -
0) - ? tracksRef.current.clientHeight - arrowIconToTracks - : 0, - top: `${topToArrowIcon + arrowIconToTracks}px`, - left: `${tracksEndPosition + trackInitOffsetPx - pixelFix}px` - }} /> - -
- { - setTimeout(() => { - let offset = 0; - if (currentTimeControlRef.current) { - const match = currentTimeControlRef.current.style.transform.match(/translate\((.+)px,/); - if (match) - offset = parseFloat(match[1]); - } - const offsetTime = commonStore.trackTotalTime / viewControlsContainerWidth * offset; - commonStore.setTrackCurrentTime(offsetTime); - }, 1); + + ) + } +) + +const AudiotrackEditor: FC<{ setPrompt: (prompt: string) => void }> = observer( + ({ setPrompt }) => { + const { t } = useTranslation() + + const viewControlsContainerRef = useRef(null) + const currentTimeControlRef = useRef(null) + const playStartTimeControlRef = useRef(null) + const tracksEndLineRef = useRef(null) + const tracksRef = useRef(null) + const toolbarRef = useRef(null) + const toolbarButtonRef = useRef(null) + const toolbarSliderRef = useRef(null) + const contentPreviewRef = useRef(null) + + const [refreshRef, setRefreshRef] = useState(false) + + const windowSize = useWindowSize() + const scale = scaleMin + scaleMax - commonStore.trackScale + + const [selectedTrackId, setSelectedTrackId] = useState('') + const playStartTimeControlX = useRef(0) + const selectedTrack = selectedTrackId + ? commonStore.tracks.find((t) => t.id === selectedTrackId) + : undefined + + useEffect(() => { + if (toolbarSliderRef.current && toolbarSliderRef.current.parentElement) + toolbarSliderRef.current.parentElement.style.removeProperty( + '--fui-Slider--steps-percent' + ) + }, []) + + const scrollContentToBottom = () => { + if (contentPreviewRef.current) + contentPreviewRef.current.scrollTop = + contentPreviewRef.current.scrollHeight + } + + useEffect(() => { + scrollContentToBottom() + }, [commonStore.recordingContent]) + + useEffect(() => { + setRefreshRef(!refreshRef) + }, [windowSize, commonStore.tracks]) + + const viewControlsContainerWidth = + toolbarRef.current && toolbarButtonRef.current && toolbarSliderRef.current + ? toolbarRef.current.clientWidth - + toolbarButtonRef.current.clientWidth - + toolbarSliderRef.current.clientWidth - + 16 // 16 = ml-2 mr-2 + : 0 + const tracksWidth = viewControlsContainerWidth + const timeOfTracksWidth = + Math.floor(tracksWidth / snapValue) * // number of moves + baseMoveTime * + scale + const currentTimeControlWidth = + timeOfTracksWidth < commonStore.trackTotalTime + ? (timeOfTracksWidth / commonStore.trackTotalTime) * + viewControlsContainerWidth + : 0 + const playStartTimeControlPosition = + ((commonStore.trackPlayStartTime - commonStore.trackCurrentTime) / + (baseMoveTime * scale)) * + snapValue + const tracksEndPosition = + ((commonStore.trackTotalTime - commonStore.trackCurrentTime) / + (baseMoveTime * scale)) * + snapValue + const moveableTracksWidth = + tracksEndLineRef.current && + viewControlsContainerRef.current && + tracksEndLineRef.current.getBoundingClientRect().left - + (viewControlsContainerRef.current.getBoundingClientRect().left + + trackInitOffsetPx) > + 0 + ? tracksEndLineRef.current.getBoundingClientRect().left - + (viewControlsContainerRef.current.getBoundingClientRect().left + + trackInitOffsetPx) + : Infinity + + return ( +
+
+ {`${commonStore.trackPlayStartTime} ms / ${commonStore.trackTotalTime} ms`} +
+
+
+ } + /> + } + onClick={() => { + commonStore.setTracks([]) + commonStore.setTrackScale(1) + commonStore.setTrackTotalTime(tracksMinimalTotalTime) + commonStore.setTrackCurrentTime(0) + commonStore.setTrackPlayStartTime(0) }} + /> +
+
+
-
- -
viewControlsContainerWidth) - && 'hidden' - )}> - { - playStartTimeControlX.current = data.lastX; +
+ +
0 + ? tracksRef.current.clientHeight - arrowIconToTracks + : 0, + top: `${topToArrowIcon + arrowIconToTracks}px`, + left: `${tracksEndPosition + trackInitOffsetPx - pixelFix}px`, + }} + /> + +
+ { - const delta = data.lastX - playStartTimeControlX.current; - let offsetTime = Math.round(Math.round(delta / snapValue * baseMoveTime * scale) / minimalMoveTime) * minimalMoveTime; - offsetTime = Math.min(Math.max( - offsetTime, - -commonStore.trackPlayStartTime), commonStore.trackTotalTime - commonStore.trackPlayStartTime); - commonStore.setTrackPlayStartTime(commonStore.trackPlayStartTime + offsetTime); + onDrag={(e, data) => { + setTimeout(() => { + let offset = 0 + if (currentTimeControlRef.current) { + const match = + currentTimeControlRef.current.style.transform.match( + /translate\((.+)px,/ + ) + if (match) offset = parseFloat(match[1]) + } + const offsetTime = + (commonStore.trackTotalTime / + viewControlsContainerWidth) * + offset + commonStore.setTrackCurrentTime(offsetTime) + }, 1) }} > -
- -
0) - ? tracksRef.current.clientHeight - : 0, - top: '50%', - left: `calc(50% - ${pixelFix}px)` - }} /> -
+
+
+ viewControlsContainerWidth) && + 'hidden' + )} + > + { + playStartTimeControlX.current = data.lastX + }} + onStop={(e, data) => { + const delta = data.lastX - playStartTimeControlX.current + let offsetTime = + Math.round( + Math.round((delta / snapValue) * baseMoveTime * scale) / + minimalMoveTime + ) * minimalMoveTime + offsetTime = Math.min( + Math.max(offsetTime, -commonStore.trackPlayStartTime), + commonStore.trackTotalTime - + commonStore.trackPlayStartTime + ) + commonStore.setTrackPlayStartTime( + commonStore.trackPlayStartTime + offsetTime + ) + }} + > +
+ +
0 + ? tracksRef.current.clientHeight + : 0, + top: '50%', + left: `calc(50% - ${pixelFix}px)`, + }} + /> +
+ +
+ + { + commonStore.setTrackScale(data.value) + }} + /> +
- - { - commonStore.setTrackScale(data.value); - }} - /> - -
-
- {commonStore.tracks.map(track => -
-
- : } - size="small" shape="circular" appearance="subtle" - onClick={() => { - flushMidiRecordingContent(); - commonStore.setPlayingTrackId(''); - - if (commonStore.recordingTrackId === track.id) { - commonStore.setRecordingTrackId(''); - } else { - if (commonStore.activeMidiDeviceIndex === -1) { - toast(t('Please select a MIDI device first'), { type: 'warning' }); - return; - } - - dropRecordingTime = true; - setSelectedTrackId(track.id); - - commonStore.setRecordingTrackId(track.id); - commonStore.setRecordingContent(track.content); - commonStore.setRecordingRawContent(track.rawContent.slice()); +
+ {commonStore.tracks.map((track) => ( +
+
+ - : } - size="small" shape="circular" appearance="subtle" - onClick={() => { - flushMidiRecordingContent(); - commonStore.setRecordingTrackId(''); + disabled={commonStore.platform === 'web'} + icon={ + commonStore.recordingTrackId === track.id ? ( + + ) : ( + + ) + } + size="small" + shape="circular" + appearance="subtle" + onClick={() => { + flushMidiRecordingContent() + commonStore.setPlayingTrackId('') + + if (commonStore.recordingTrackId === track.id) { + commonStore.setRecordingTrackId('') + } else { + if (commonStore.activeMidiDeviceIndex === -1) { + toast(t('Please select a MIDI device first'), { + type: 'warning', + }) + return + } - if (commonStore.playingTrackId === track.id) { - commonStore.setPlayingTrackId(''); - } else { - setSelectedTrackId(track.id); + dropRecordingTime = true + setSelectedTrackId(track.id) - commonStore.setPlayingTrackId(track.id); + commonStore.setRecordingTrackId(track.id) + commonStore.setRecordingContent(track.content) + commonStore.setRecordingRawContent( + track.rawContent.slice() + ) + } + }} + /> + - } size="small" shape="circular" - appearance="subtle" onClick={() => { - const tracks = commonStore.tracks.slice().filter(t => t.id !== track.id); - commonStore.setTracks(tracks); - refreshTracksTotalTime(); - }} /> -
-
-
- + ) : ( + + ) + } + size="small" + shape="circular" + appearance="subtle" + onClick={() => { + flushMidiRecordingContent() + commonStore.setRecordingTrackId('') + + if (commonStore.playingTrackId === track.id) { + commonStore.setPlayingTrackId('') + } else { + setSelectedTrackId(track.id) + + commonStore.setPlayingTrackId(track.id) + } + }} + /> + } + size="small" + shape="circular" + appearance="subtle" + onClick={() => { + const tracks = commonStore.tracks + .slice() + .filter((t) => t.id !== track.id) + commonStore.setTracks(tracks) + refreshTracksTotalTime() + }} />
+
+
+ +
+
-
)} -
-
- - + + OpenFileDialog('*.mid').then(async (blob) => { + const bodyForm = new FormData() + bodyForm.append('file_data', blob) + const { url, headers } = await getReqUrl( + commonStore.getCurrentModelConfig().apiParameters.apiPort, + '/midi-to-text' + ) + fetch(url, { + method: 'POST', + headers, + body: bodyForm, + }) + .then(async (r) => { + if (r.status === 200) { + const text = (await r.json()).text as string + const rawContent = text + .split(' ') + .map(tokenToMidiMessage) + .filter((m) => m) as MidiMessage[] + const tracks = commonStore.tracks.slice() + + tracks.push({ + id: uuid(), + mainInstrument: + getMidiRawContentMainInstrument(rawContent), + content: text, + rawContent: rawContent, + offsetTime: 0, + contentTime: getMidiRawContentTime(rawContent), + }) + commonStore.setTracks(tracks) + refreshTracksTotalTime() + } else { + toast( + 'Failed to fetch - ' + + r.status + + ' - ' + + r.statusText + + ' - ' + + (await r.text()), + { + type: 'error', + } + ) + } + }) + .catch((e) => { + toast(t('Error') + ' - ' + (e.message || e), { + type: 'error', + autoClose: 2500, + }) + }) + }) + }} + > + {t('Import MIDI')} + +
+ {t('Select a track to preview the content')}
- - {t('Select a track to preview the content')} -
-
-
- {selectedTrack && - -
- {`${t('Start Time')}: ${selectedTrack.offsetTime} ms`} - {`${t('Content Duration')}: ${selectedTrack.contentTime} ms`} -
- {selectedTrackId === commonStore.recordingTrackId - ? commonStore.recordingContent - : selectedTrack.content} +
+ {selectedTrack && ( + +
+ {`${t('Start Time')}: ${selectedTrack.offsetTime} ms`} + {`${t('Content Duration')}: ${selectedTrack.contentTime} ms`} +
+ {selectedTrackId === commonStore.recordingTrackId + ? commonStore.recordingContent + : selectedTrack.content} +
+
+ )} + {commonStore.platform !== 'web' && ( +
+ {t('Current Instrument') + ':'} + {InstrumentTypeNameMap.map((name, i) => ( + + {t(name)} + + ))}
- - } - { - commonStore.platform !== 'web' && -
- {t('Current Instrument') + ':'} - {InstrumentTypeNameMap.map((name, i) => - {t(name)})} -
- } - - - -
- ); -}); - -export default AudiotrackEditor; + const result = ( + ' ' + globalMessages.map(midiMessageToToken).join('') + ).trim() + commonStore.setCompositionSubmittedPrompt(result) + setPrompt(result) + }} + > + {t('Save to generation area')} + + +
+ ) + } +) + +export default AudiotrackEditor diff --git a/frontend/src/pages/Chat.tsx b/frontend/src/pages/Chat.tsx index 6649ac00..7edeffce 100644 --- a/frontend/src/pages/Chat.tsx +++ b/frontend/src/pages/Chat.tsx @@ -1,5 +1,5 @@ -import React, { FC, useCallback, useEffect, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; +import React, { FC, useCallback, useEffect, useRef, useState } from 'react' +import { AvatarProps } from '@fluentui/react-avatar' import { Avatar, Button, @@ -8,17 +8,8 @@ import { MenuTrigger, PresenceBadge, Switch, - Textarea -} from '@fluentui/react-components'; -import commonStore, { ModelStatus } from '../stores/commonStore'; -import { observer } from 'mobx-react-lite'; -import { v4 as uuid } from 'uuid'; -import classnames from 'classnames'; -import { fetchEventSource } from '@microsoft/fetch-event-source'; -import { KebabHorizontalIcon, PencilIcon, SyncIcon, TrashIcon } from '@primer/octicons-react'; -import logo from '../assets/images/logo.png'; -import MarkdownRender from '../components/MarkdownRender'; -import { ToolTipButton } from '../components/ToolTipButton'; + Textarea, +} from '@fluentui/react-components' import { ArrowCircleUp28Regular, ArrowClockwise16Regular, @@ -30,14 +21,45 @@ import { RecordStop28Regular, SaveRegular, TextAlignJustify24Regular, - TextAlignJustifyRotate9024Regular -} from '@fluentui/react-icons'; -import { CopyButton } from '../components/CopyButton'; -import { ReadButton } from '../components/ReadButton'; -import { toast } from 'react-toastify'; -import { WorkHeader } from '../components/WorkHeader'; -import { DialogButton } from '../components/DialogButton'; -import { OpenFileFolder, OpenOpenFileDialog, OpenSaveFileDialog } from '../../wailsjs/go/backend_golang/App'; + TextAlignJustifyRotate9024Regular, +} from '@fluentui/react-icons' +import { fetchEventSource } from '@microsoft/fetch-event-source' +import { + KebabHorizontalIcon, + PencilIcon, + SyncIcon, + TrashIcon, +} from '@primer/octicons-react' +import classnames from 'classnames' +import { observer } from 'mobx-react-lite' +import { useTranslation } from 'react-i18next' +import { toast } from 'react-toastify' +import { useMediaQuery } from 'usehooks-ts' +import { v4 as uuid } from 'uuid' +import { + OpenFileFolder, + OpenOpenFileDialog, + OpenSaveFileDialog, +} from '../../wailsjs/go/backend_golang/App' +import logo from '../assets/images/logo.png' +import { CopyButton } from '../components/CopyButton' +import { DialogButton } from '../components/DialogButton' +import { Labeled } from '../components/Labeled' +import MarkdownRender from '../components/MarkdownRender' +import { ReadButton } from '../components/ReadButton' +import { ToolTipButton } from '../components/ToolTipButton' +import { ValuedSlider } from '../components/ValuedSlider' +import { WorkHeader } from '../components/WorkHeader' +import commonStore, { ModelStatus } from '../stores/commonStore' +import { + botName, + ConversationMessage, + MessageType, + Role, + systemName, + userName, + welcomeUuid, +} from '../types/chat' import { absPathAsset, bytesToReadable, @@ -45,400 +67,659 @@ import { newChatConversation, OpenFileDialog, setActivePreset, - toastWithButton -} from '../utils'; -import { useMediaQuery } from 'usehooks-ts'; -import { botName, ConversationMessage, MessageType, Role, systemName, userName, welcomeUuid } from '../types/chat'; -import { Labeled } from '../components/Labeled'; -import { ValuedSlider } from '../components/ValuedSlider'; -import { PresetsButton } from './PresetsManager/PresetsButton'; -import { webOpenOpenFileDialog } from '../utils/web-file-operations'; -import { defaultPenaltyDecay } from './defaultConfigs'; -import { AvatarProps } from '@fluentui/react-avatar'; + toastWithButton, +} from '../utils' +import { webOpenOpenFileDialog } from '../utils/web-file-operations' +import { defaultPenaltyDecay } from './defaultConfigs' +import { PresetsButton } from './PresetsManager/PresetsButton' let chatSseControllers: { [id: string]: AbortController -} = {}; +} = {} const MoreUtilsButton: FC<{ - uuid: string, + uuid: string setEditing: (editing: boolean) => void -}> = observer(({ - uuid, - setEditing -}) => { - const { t } = useTranslation(); - const [speaking, setSpeaking] = useState(false); - - const messageItem = commonStore.conversation[uuid]; - - return - - ; -}); +}> = observer(({ uuid, setEditing }) => { + const { t } = useTranslation() + const [speaking, setSpeaking] = useState(false) + + const messageItem = commonStore.conversation[uuid] + + return ( + + + + ) +}) const HiddenAvatar: FC = ({ children, hidden, ...props }) => { if (hidden) { - return
{children}
; + return
{children}
} else { - return ( - - {children} - - ); + return {children} } -}; +} const ChatMessageItem: FC<{ - uuid: string, - onSubmit: (message: string | null, answerId: string | null, - startUuid: string | null, endUuid: string | null, includeEndUuid: boolean) => void + uuid: string + onSubmit: ( + message: string | null, + answerId: string | null, + startUuid: string | null, + endUuid: string | null, + includeEndUuid: boolean + ) => void }> = observer(({ uuid, onSubmit }) => { - const { t } = useTranslation(); - const [editing, setEditing] = useState(false); - const textareaRef = useRef(null); - const messageItem = commonStore.conversation[uuid]; + const { t } = useTranslation() + const [editing, setEditing] = useState(false) + const textareaRef = useRef(null) + const messageItem = commonStore.conversation[uuid] - console.log(uuid); + console.log(uuid) const setEditingInner = (editing: boolean) => { - setEditing(editing); + setEditing(editing) if (editing) { setTimeout(() => { - const textarea = textareaRef.current; + const textarea = textareaRef.current if (textarea) { - textarea.focus(); - textarea.selectionStart = textarea.value.length; - textarea.selectionEnd = textarea.value.length; - textarea.style.height = textarea.scrollHeight + 'px'; + textarea.focus() + textarea.selectionStart = textarea.value.length + textarea.selectionEnd = textarea.value.length + textarea.style.height = textarea.scrollHeight + 'px' } - }); + }) } - }; + } - let avatarImg: string | undefined; + let avatarImg: string | undefined if (commonStore.activePreset && messageItem.sender === botName) { - avatarImg = absPathAsset(commonStore.activePreset.avatarImg); + avatarImg = absPathAsset(commonStore.activePreset.avatarImg) } else if (commonStore.activePreset && messageItem.sender === userName) { - avatarImg = commonStore.activePreset.userAvatarImg && absPathAsset(commonStore.activePreset.userAvatarImg); + avatarImg = + commonStore.activePreset.userAvatarImg && + absPathAsset(commonStore.activePreset.userAvatarImg) } else if (messageItem.avatarImg) { - avatarImg = messageItem.avatarImg; + avatarImg = messageItem.avatarImg } - return
{ - const utils = document.getElementById('utils-' + uuid); - if (utils) utils.classList.remove('invisible'); - }} - onMouseLeave={() => { - const utils = document.getElementById('utils-' + uuid); - if (utils) utils.classList.add('invisible'); - }} - > -
+ )} +
+ } + /> + ) +}) -export default Settings; +export default Settings diff --git a/frontend/src/pages/Train.tsx b/frontend/src/pages/Train.tsx index 77f42b7f..f9e728cc 100644 --- a/frontend/src/pages/Train.tsx +++ b/frontend/src/pages/Train.tsx @@ -1,6 +1,36 @@ -import React, { FC, useEffect, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Button, Dropdown, Input, Option, Select, Switch, Tab, TabList } from '@fluentui/react-components'; +import React, { FC, useEffect, useRef, useState } from 'react' +import { + Button, + Dropdown, + Input, + Option, + Select, + Switch, + Tab, + TabList, +} from '@fluentui/react-components' +import { + DataUsageSettings20Regular, + Folder20Regular, +} from '@fluentui/react-icons' +import { SelectTabEventHandler } from '@fluentui/react-tabs' +import { + CategoryScale, + Chart as ChartJS, + Legend, + LinearScale, + LineElement, + PointElement, + Title, + Tooltip, +} from 'chart.js' +import { t } from 'i18next' +import { observer } from 'mobx-react-lite' +import { Line } from 'react-chartjs-2' +import { ChartJSOrUndefined } from 'react-chartjs-2/dist/types' +import { useTranslation } from 'react-i18next' +import { useNavigate } from 'react-router' +import { toast } from 'react-toastify' import { ConvertData, FileExists, @@ -12,39 +42,21 @@ import { WslInstallUbuntu, WslIsEnabled, WslStart, - WslStop -} from '../../wailsjs/go/backend_golang/App'; -import { toast } from 'react-toastify'; -import commonStore from '../stores/commonStore'; -import { observer } from 'mobx-react-lite'; -import { SelectTabEventHandler } from '@fluentui/react-tabs'; -import { checkDependencies, toastWithButton } from '../utils'; -import { Section } from '../components/Section'; -import { Labeled } from '../components/Labeled'; -import { ToolTipButton } from '../components/ToolTipButton'; -import { DataUsageSettings20Regular, Folder20Regular } from '@fluentui/react-icons'; -import { useNavigate } from 'react-router'; -import { - CategoryScale, - Chart as ChartJS, - Legend, - LinearScale, - LineElement, - PointElement, - Title, - Tooltip -} from 'chart.js'; -import { Line } from 'react-chartjs-2'; -import { ChartJSOrUndefined } from 'react-chartjs-2/dist/types'; -import { WindowShow } from '../../wailsjs/runtime'; -import { t } from 'i18next'; -import { DialogButton } from '../components/DialogButton'; + WslStop, +} from '../../wailsjs/go/backend_golang/App' +import { WindowShow } from '../../wailsjs/runtime' +import { DialogButton } from '../components/DialogButton' +import { Labeled } from '../components/Labeled' +import { Section } from '../components/Section' +import { ToolTipButton } from '../components/ToolTipButton' +import commonStore from '../stores/commonStore' import { DataProcessParameters, LoraFinetuneParameters, LoraFinetunePrecision, - TrainNavigationItem -} from '../types/train'; + TrainNavigationItem, +} from '../types/train' +import { checkDependencies, toastWithButton } from '../utils' ChartJS.register( CategoryScale, @@ -54,49 +66,66 @@ ChartJS.register( Tooltip, Title, Legend -); +) const parseLossData = (data: string) => { - const regex = /Epoch (\d+):\s+(\d+%)\|[\s\S]*\| (\d+)\/(\d+) \[(\S+)<(\S+),\s+(\S+), loss=(\S+),[\s\S]*\]/g; - const matches = Array.from(data.matchAll(regex)); - if (matches.length === 0) - return false; - const lastMatch = matches[matches.length - 1]; - const epoch = parseInt(lastMatch[1]); - const loss = parseFloat(lastMatch[8]); - commonStore.setChartTitle(`Epoch ${epoch}: ${lastMatch[2]} - ${lastMatch[3]}/${lastMatch[4]} - ${lastMatch[5]}/${lastMatch[6]} - ${lastMatch[7]} Loss=${loss}`); - addLossDataToChart(epoch, loss); + const regex = + /Epoch (\d+):\s+(\d+%)\|[\s\S]*\| (\d+)\/(\d+) \[(\S+)<(\S+),\s+(\S+), loss=(\S+),[\s\S]*\]/g + const matches = Array.from(data.matchAll(regex)) + if (matches.length === 0) return false + const lastMatch = matches[matches.length - 1] + const epoch = parseInt(lastMatch[1]) + const loss = parseFloat(lastMatch[8]) + commonStore.setChartTitle( + `Epoch ${epoch}: ${lastMatch[2]} - ${lastMatch[3]}/${lastMatch[4]} - ${lastMatch[5]}/${lastMatch[6]} - ${lastMatch[7]} Loss=${loss}` + ) + addLossDataToChart(epoch, loss) if (loss > 5) - toast(t('Loss is too high, please check the training data, and ensure your gpu driver is up to date.'), { - type: 'warning', - toastId: 'train_loss_high' - }); - return true; -}; + toast( + t( + 'Loss is too high, please check the training data, and ensure your gpu driver is up to date.' + ), + { + type: 'warning', + toastId: 'train_loss_high', + } + ) + return true +} -let chartLine: ChartJSOrUndefined<'line', (number | null)[], string>; +let chartLine: ChartJSOrUndefined<'line', (number | null)[], string> const addLossDataToChart = (epoch: number, loss: number) => { - const epochIndex = commonStore.chartData.labels!.findIndex(l => l.includes(epoch.toString())); + const epochIndex = commonStore.chartData.labels!.findIndex((l) => + l.includes(epoch.toString()) + ) if (epochIndex === -1) { if (epoch === 0) { - commonStore.chartData.labels!.push('Init'); - commonStore.chartData.datasets[0].data = [...commonStore.chartData.datasets[0].data, loss]; + commonStore.chartData.labels!.push('Init') + commonStore.chartData.datasets[0].data = [ + ...commonStore.chartData.datasets[0].data, + loss, + ] } - commonStore.chartData.labels!.push('Epoch ' + epoch.toString()); - commonStore.chartData.datasets[0].data = [...commonStore.chartData.datasets[0].data, loss]; + commonStore.chartData.labels!.push('Epoch ' + epoch.toString()) + commonStore.chartData.datasets[0].data = [ + ...commonStore.chartData.datasets[0].data, + loss, + ] } else { if (chartLine) { - const newData = [...commonStore.chartData.datasets[0].data]; - newData[epochIndex] = loss; - chartLine.data.datasets[0].data = newData; - chartLine.update(); + const newData = [...commonStore.chartData.datasets[0].data] + newData[epochIndex] = loss + chartLine.data.datasets[0].data = newData + chartLine.update() } } - commonStore.setChartData(commonStore.chartData); -}; + commonStore.setChartData(commonStore.chartData) +} -const loraFinetuneParametersOptions: Array<[key: keyof LoraFinetuneParameters, type: string, name: string]> = [ +const loraFinetuneParametersOptions: Array< + [key: keyof LoraFinetuneParameters, type: string, name: string] +> = [ ['devices', 'number', 'Devices'], ['precision', 'LoraFinetunePrecision', 'Precision'], ['gradCp', 'boolean', 'Gradient Checkpoint'], @@ -116,318 +145,440 @@ const loraFinetuneParametersOptions: Array<[key: keyof LoraFinetuneParameters, t ['loraR', 'number', 'LoRA R'], ['loraAlpha', 'number', 'LoRA Alpha'], ['loraDropout', 'number', 'LoRA Dropout'], - ['beta1', 'any', ''] + ['beta1', 'any', ''], // ['preFfn', 'boolean', 'Pre-FFN'], // ['headQk', 'boolean', 'Head QK'] -]; +] const showError = (e: any) => { - const msg = e.message || e; + const msg = e.message || e if (msg === 'wsl not running') { - toast(t('WSL is not running, please retry. If it keeps happening, it means you may be using an outdated version of WSL, run "wsl --update" to update.'), { type: 'error' }); + toast( + t( + 'WSL is not running, please retry. If it keeps happening, it means you may be using an outdated version of WSL, run "wsl --update" to update.' + ), + { type: 'error' } + ) } else { - toast(t(msg), { type: 'error', toastId: 'train_error' }); + toast(t(msg), { type: 'error', toastId: 'train_error' }) } -}; +} // error key should be lowercase const errorsMap = Object.entries({ - ['python3 ./finetune/lora/$modelInfo'.toLowerCase()]: 'Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.', + ['python3 ./finetune/lora/$modelInfo'.toLowerCase()]: + 'Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.', 'cuda out of memory': 'VRAM is not enough', - 'valueerror: high <= 0': 'Training data is not enough, reduce context length or add more data for training', - '+= \'+ptx\'': 'Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run "wsl --set-version Ubuntu-22.04 2"', - 'size mismatch for blocks': 'Size mismatch for blocks. You are attempting to continue training from the LoRA model, but it does not match the base model. Please set LoRA model to None.', + 'valueerror: high <= 0': + 'Training data is not enough, reduce context length or add more data for training', + "+= '+ptx'": + 'Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run "wsl --set-version Ubuntu-22.04 2"', + 'size mismatch for blocks': + 'Size mismatch for blocks. You are attempting to continue training from the LoRA model, but it does not match the base model. Please set LoRA model to None.', 'cuda_home environment variable is not set': 'Matched CUDA is not installed', 'unsupported gpu architecture': 'Matched CUDA is not installed', - 'error building extension \'fused_adam\'': 'Matched CUDA is not installed', - 'rwkv{version} is not supported': 'This version of RWKV is not supported yet.', - 'no such file': 'Failed to find the base model, please try to change your base model.', - 'modelinfo is invalid': 'Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.' -}); + "error building extension 'fused_adam'": 'Matched CUDA is not installed', + 'rwkv{version} is not supported': + 'This version of RWKV is not supported yet.', + 'no such file': + 'Failed to find the base model, please try to change your base model.', + 'modelinfo is invalid': + 'Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.', +}) export const wslHandler = (data: string) => { if (data) { - addWslMessage(data); - const ok = parseLossData(data); + addWslMessage(data) + const ok = parseLossData(data) if (!ok) for (const [key, value] of errorsMap) { if (data.toLowerCase().includes(key)) { - showError(value); - return; + showError(value) + return } } } -}; +} const addWslMessage = (message: string) => { - const newData = commonStore.wslStdout + '\n' + message; - let lines = newData.split('\n'); - const result = lines.slice(-100).join('\n'); - commonStore.setWslStdout(result); -}; + const newData = commonStore.wslStdout + '\n' + message + let lines = newData.split('\n') + const result = lines.slice(-100).join('\n') + commonStore.setWslStdout(result) +} const TerminalDisplay: FC = observer(() => { - const bodyRef = useRef(null); + const bodyRef = useRef(null) const scrollToBottom = () => { if (bodyRef.current) - bodyRef.current.scrollTop = bodyRef.current.scrollHeight; - }; + bodyRef.current.scrollTop = bodyRef.current.scrollHeight + } useEffect(() => { - scrollToBottom(); - }); + scrollToBottom() + }) return ( -
-
- {commonStore.wslStdout} -
+
+
{commonStore.wslStdout}
- ); -}); + ) +}) const Terminal: FC = observer(() => { - const { t } = useTranslation(); - const [input, setInput] = useState(''); + const { t } = useTranslation() + const [input, setInput] = useState('') const handleKeyDown = (e: any) => { - e.stopPropagation(); + e.stopPropagation() if (e.keyCode === 13) { - e.preventDefault(); - if (!input) return; - - WslStart().then(() => { - addWslMessage('WSL> ' + input); - setInput(''); - WslCommand(input).then(WindowShow).catch(showError); - }).catch(showError); + e.preventDefault() + if (!input) return + + WslStart() + .then(() => { + addWslMessage('WSL> ' + input) + setInput('') + WslCommand(input).then(WindowShow).catch(showError) + }) + .catch(showError) } - }; + } return ( -
+
-
+
WSL: - { - setInput(e.target.value); - }} onKeyDown={handleKeyDown}> -
- ); -}); + ) +}) const LoraFinetune: FC = observer(() => { - const { t } = useTranslation(); - const navigate = useNavigate(); - const chartRef = useRef>(null); + const { t } = useTranslation() + const navigate = useNavigate() + const chartRef = + useRef>(null) - const dataParams = commonStore.dataProcessParams; - const loraParams = commonStore.loraFinetuneParams; + const dataParams = commonStore.dataProcessParams + const loraParams = commonStore.loraFinetuneParams - if (chartRef.current) - chartLine = chartRef.current; + if (chartRef.current) chartLine = chartRef.current const setDataParams = (newParams: Partial) => { commonStore.setDataProcessParams({ ...dataParams, - ...newParams - }); - }; + ...newParams, + }) + } const setLoraParams = (newParams: Partial) => { commonStore.setLoraFinetuneParameters({ ...loraParams, - ...newParams - }); - }; + ...newParams, + }) + } useEffect(() => { if (loraParams.baseModel === '') setLoraParams({ - baseModel: commonStore.modelSourceList.find(m => m.isComplete)?.name || '' - }); - }, []); + baseModel: + commonStore.modelSourceList.find((m) => m.isComplete)?.name || '', + }) + }, []) const StartLoraFinetune = async () => { - const ok = await checkDependencies(navigate); - if (!ok) - return; - - const convertedDataPath = './finetune/json2binidx_tool/data/' + - dataParams.dataPath.replace(/[\/\\]$/, '').split(/[\/\\]/).pop()!.split('.')[0] + - '_text_document'; - if (!await FileExists(convertedDataPath + '.idx')) { - toast(t('Please convert data first.'), { type: 'error' }); - return; + const ok = await checkDependencies(navigate) + if (!ok) return + + const convertedDataPath = + './finetune/json2binidx_tool/data/' + + dataParams.dataPath + .replace(/[\/\\]$/, '') + .split(/[\/\\]/) + .pop()! + .split('.')[0] + + '_text_document' + if (!(await FileExists(convertedDataPath + '.idx'))) { + toast(t('Please convert data first.'), { type: 'error' }) + return } - WslIsEnabled().then(() => { - WslStart().then(() => { - setTimeout(WindowShow, 1000); - - let ctxLen = loraParams.ctxLen; - if (dataParams.dataPath === 'finetune/data/sample.jsonl') { - ctxLen = 150; - toast(t('You are using sample data for training. For formal training, please make sure to create your own jsonl file.'), { - type: 'info', - autoClose: 6000 - }); - } + WslIsEnabled() + .then(() => { + WslStart() + .then(() => { + setTimeout(WindowShow, 1000) + + let ctxLen = loraParams.ctxLen + if (dataParams.dataPath === 'finetune/data/sample.jsonl') { + ctxLen = 150 + toast( + t( + 'You are using sample data for training. For formal training, please make sure to create your own jsonl file.' + ), + { + type: 'info', + autoClose: 6000, + } + ) + } - commonStore.setChartData({ - labels: [], - datasets: [ - { - label: 'Loss', - data: [], - borderColor: 'rgb(53, 162, 235)', - backgroundColor: 'rgba(53, 162, 235, 0.5)' + commonStore.setChartData({ + labels: [], + datasets: [ + { + label: 'Loss', + data: [], + borderColor: 'rgb(53, 162, 235)', + backgroundColor: 'rgba(53, 162, 235, 0.5)', + }, + ], + }) + WslCommand( + `export cnMirror=${commonStore.settings.cnMirror ? '1' : '0'} ` + + `&& export loadModel=models/${loraParams.baseModel} ` + + `&& sed -i 's/\\r$//' finetune/install-wsl-dep-and-train.sh ` + + `&& chmod +x finetune/install-wsl-dep-and-train.sh && ./finetune/install-wsl-dep-and-train.sh ` + + (loraParams.baseModel + ? `--load_model models/${loraParams.baseModel} ` + : '') + + (loraParams.loraLoad + ? `--lora_load lora-models/${loraParams.loraLoad} ` + : '') + + `--data_file ${convertedDataPath} ` + + `--ctx_len ${ctxLen} --epoch_steps ${loraParams.epochSteps} --epoch_count ${loraParams.epochCount} ` + + `--epoch_begin ${loraParams.epochBegin} --epoch_save ${loraParams.epochSave} ` + + `--micro_bsz ${loraParams.microBsz} --accumulate_grad_batches ${loraParams.accumGradBatches} ` + + `--pre_ffn ${loraParams.preFfn ? '0' : '0'} --head_qk ${loraParams.headQk ? '0' : '0'} --lr_init ${loraParams.lrInit} --lr_final ${loraParams.lrFinal} ` + + `--warmup_steps ${loraParams.warmupSteps} ` + + `--beta1 ${loraParams.beta1} --beta2 ${loraParams.beta2} --adam_eps ${loraParams.adamEps} ` + + `--devices ${loraParams.devices} --precision ${loraParams.precision} ` + + `--grad_cp ${loraParams.gradCp ? '1' : '0'} ` + + `--lora_r ${loraParams.loraR} --lora_alpha ${loraParams.loraAlpha} --lora_dropout ${loraParams.loraDropout}` + ).catch(showError) + }) + .catch((e) => { + WindowShow() + const msg = e.message || e + if ( + msg === 'ubuntu not found' || + msg.includes('could not obtain registered distros') + ) { + toastWithButton( + t('Ubuntu is not installed, do you want to install it?'), + t('Install Ubuntu'), + () => { + WslInstallUbuntu() + .then(() => { + WindowShow() + toast( + t( + 'Please install Ubuntu using Microsoft Store, after installation click the Open button in Microsoft Store and then click the Train button' + ), + { + type: 'info', + autoClose: 10000, + } + ) + }) + .catch(showError) + } + ) + } else { + showError(msg) + } + }) + }) + .catch((e) => { + const msg = e.message || e + + const enableWsl = (forceMode: boolean) => { + WindowShow() + toastWithButton( + t('WSL is not enabled, do you want to enable it?'), + t('Enable WSL'), + () => { + WslEnable(forceMode) + .then(() => { + WindowShow() + toast( + t( + 'After installation, please restart your computer to enable WSL' + ), + { + type: 'info', + autoClose: false, + } + ) + }) + .catch(showError) } - ] - }); - WslCommand(`export cnMirror=${commonStore.settings.cnMirror ? '1' : '0'} ` + - `&& export loadModel=models/${loraParams.baseModel} ` + - `&& sed -i 's/\\r$//' finetune/install-wsl-dep-and-train.sh ` + - `&& chmod +x finetune/install-wsl-dep-and-train.sh && ./finetune/install-wsl-dep-and-train.sh ` + - (loraParams.baseModel ? `--load_model models/${loraParams.baseModel} ` : '') + - (loraParams.loraLoad ? `--lora_load lora-models/${loraParams.loraLoad} ` : '') + - `--data_file ${convertedDataPath} ` + - `--ctx_len ${ctxLen} --epoch_steps ${loraParams.epochSteps} --epoch_count ${loraParams.epochCount} ` + - `--epoch_begin ${loraParams.epochBegin} --epoch_save ${loraParams.epochSave} ` + - `--micro_bsz ${loraParams.microBsz} --accumulate_grad_batches ${loraParams.accumGradBatches} ` + - `--pre_ffn ${loraParams.preFfn ? '0' : '0'} --head_qk ${loraParams.headQk ? '0' : '0'} --lr_init ${loraParams.lrInit} --lr_final ${loraParams.lrFinal} ` + - `--warmup_steps ${loraParams.warmupSteps} ` + - `--beta1 ${loraParams.beta1} --beta2 ${loraParams.beta2} --adam_eps ${loraParams.adamEps} ` + - `--devices ${loraParams.devices} --precision ${loraParams.precision} ` + - `--grad_cp ${loraParams.gradCp ? '1' : '0'} ` + - `--lora_r ${loraParams.loraR} --lora_alpha ${loraParams.loraAlpha} --lora_dropout ${loraParams.loraDropout}`).catch(showError); - }).catch(e => { - WindowShow(); - const msg = e.message || e; - if (msg === 'ubuntu not found') { - toastWithButton(t('Ubuntu is not installed, do you want to install it?'), t('Install Ubuntu'), () => { - WslInstallUbuntu().then(() => { - WindowShow(); - toast(t('Please install Ubuntu using Microsoft Store, after installation click the Open button in Microsoft Store and then click the Train button'), { - type: 'info', - autoClose: 10000 - }); - }).catch(showError); - }); + ) + } + + if (msg === 'wsl is not enabled') { + enableWsl(true) + } else if (msg.includes('wsl.state: The system cannot find the file')) { + enableWsl(true) } else { - showError(msg); + showError(msg) } - }); - }).catch(e => { - const msg = e.message || e; - - const enableWsl = (forceMode: boolean) => { - WindowShow(); - toastWithButton(t('WSL is not enabled, do you want to enable it?'), t('Enable WSL'), () => { - WslEnable(forceMode).then(() => { - WindowShow(); - toast(t('After installation, please restart your computer to enable WSL'), { - type: 'info', - autoClose: false - }); - }).catch(showError); - }); - }; - - if (msg === 'wsl is not enabled') { - enableWsl(true); - } else if (msg.includes('wsl.state: The system cannot find the file')) { - enableWsl(true); - } else { - showError(msg); - } - }); - }; + }) + } return ( -
- {(commonStore.wslStdout.length > 0 || commonStore.chartData.labels!.length !== 0) && +
+ {(commonStore.wslStdout.length > 0 || + commonStore.chartData.labels!.length !== 0) && (
- {commonStore.wslStdout.length > 0 && commonStore.chartData.labels!.length === 0 && } - {commonStore.chartData.labels!.length !== 0 && - 0 && + commonStore.chartData.labels!.length === 0 && } + {commonStore.chartData.labels!.length !== 0 && ( + } + scales: { + y: { + beginAtZero: true, + }, + }, + maintainAspectRatio: false, + }} + style={{ width: '100%' }} + /> + )}
- } + )}
-
+
{t('Data Path')} - { - setDataParams({ dataPath: data.value }); - }} /> - - } onClick={() => { - OpenFileFolder(dataParams.dataPath); - }} /> + setDataParams({ dataPath: data.value }) + }} + /> + + } + onClick={() => { + OpenFileFolder(dataParams.dataPath) + }} + />
-
+
{t('Vocab Path')} - { - setDataParams({ vocabPath: data.value }); - }} /> - + setDataParams({ vocabPath: data.value }) + }} + /> +
} @@ -436,158 +587,220 @@ const LoraFinetune: FC = observer(() => {
-
-
- {t('Base Model')} -
- { setLoraParams({ - baseModel: data.value - }); - }}> - {commonStore.modelSourceList.map((modelItem, index) => - modelItem.isComplete && + baseModel: data.value, + }) + }} + > + {commonStore.modelSourceList.map( + (modelItem, index) => + modelItem.isComplete && ( + + ) )} - } onClick={() => { - navigate({ pathname: '/models' }); - }} /> + } + onClick={() => { + navigate({ pathname: '/models' }) + }} + />
-
+
{t('LoRA Model')} - - +
- { - loraFinetuneParametersOptions.map(([key, type, name], index) => { - return ( - { + return ( + { setLoraParams({ - [key]: Number(data.value) - }); - }} /> : - type === 'boolean' ? - { + [key]: Number(data.value), + }) + }} + /> + ) : type === 'boolean' ? ( + { + setLoraParams({ + [key]: data.checked, + }) + }} + /> + ) : type === 'string' ? ( + { + setLoraParams({ + [key]: data.value, + }) + }} + /> + ) : type === 'LoraFinetunePrecision' ? ( + { + if (data.optionText) { setLoraParams({ - [key]: data.checked - }); - }} /> : - type === 'string' ? - { - setLoraParams({ - [key]: data.value - }); - }} /> : - type === 'LoraFinetunePrecision' ? - { - if (data.optionText) { - setLoraParams({ - precision: data.optionText as LoraFinetunePrecision - }); - } - }} - > - - - - - :
- } /> - ); - }) - } + precision: + data.optionText as LoraFinetunePrecision, + }) + } + }} + > + + + + + ) : ( +
+ ) + } + /> + ) + })}
} />
- - + +
- ); -}); + ) +}) const pages: { [label: string]: TrainNavigationItem } = { 'LoRA Finetune': { - element: + element: , }, WSL: { - element: - } -}; - + element: , + }, +} const Train: FC = () => { - const { t } = useTranslation(); - const [tab, setTab] = useState('LoRA Finetune'); + const { t } = useTranslation() + const [tab, setTab] = useState('LoRA Finetune') const selectTab: SelectTabEventHandler = (e, data) => - typeof data.value === 'string' ? setTab(data.value) : null; - - return
- - {Object.entries(pages).map(([label]) => ( - - {t(label)} - - ))} - -
- {pages[tab].element} + typeof data.value === 'string' ? setTab(data.value) : null + + return ( +
+ + {Object.entries(pages).map(([label]) => ( + + {t(label)} + + ))} + +
{pages[tab].element}
-
; -}; + ) +} -export default Train; +export default Train diff --git a/frontend/src/pages/defaultConfigs.ts b/frontend/src/pages/defaultConfigs.ts index c901dc4d..3bb5409d 100644 --- a/frontend/src/pages/defaultConfigs.ts +++ b/frontend/src/pages/defaultConfigs.ts @@ -1,10 +1,11 @@ -import { CompletionPreset } from '../types/completion'; -import { ModelConfig } from '../types/configs'; +import { CompletionPreset } from '../types/completion' +import { ModelConfig } from '../types/configs' -export const defaultPenaltyDecay = 0.996; +export const defaultPenaltyDecay = 0.996 -export const defaultCompositionPrompt = ''; -export const defaultCompositionABCPrompt = 'S:3\n' + +export const defaultCompositionPrompt = '' +export const defaultCompositionABCPrompt = + 'S:3\n' + 'B:9\n' + 'E:4\n' + 'B:9\n' + @@ -14,186 +15,205 @@ export const defaultCompositionABCPrompt = 'S:3\n' + 'L:1/8\n' + 'M:3/4\n' + 'K:D\n' + - ' Bc |"G" d2 cB"A" A2 FE |"Bm" F2 B4 F^G |'; + ' Bc |"G" d2 cB"A" A2 FE |"Bm" F2 B4 F^G |' -export const defaultPresets: CompletionPreset[] = [{ - name: 'Writer', - prompt: 'The following is an epic science fiction masterpiece that is immortalized, with delicate descriptions and grand depictions of interstellar civilization wars.\n' + - 'Chapter 1.\n', - params: { - maxResponseToken: 500, - temperature: 1, - topP: 0.3, - presencePenalty: 0, - frequencyPenalty: 1, - stop: '\\n\\nUser', - injectStart: '', - injectEnd: '' - } -}, { - name: 'Translator', - prompt: 'Translate this into Chinese.\n' + - '\n' + - 'English: What rooms do you have available?', - params: { - maxResponseToken: 500, - temperature: 1, - topP: 0.3, - presencePenalty: 0, - frequencyPenalty: 1, - stop: '\\n\\n', - injectStart: '\\nChinese: ', - injectEnd: '\\n\\nEnglish: ' - } -}, { - name: 'Catgirl', - prompt: 'The following is a conversation between a cat girl and her owner. The cat girl is a humanized creature that behaves like a cat but is humanoid. At the end of each sentence in the dialogue, she will add "Meow~". In the following content, User represents the owner and Assistant represents the cat girl.\n' + - '\n' + - 'User: Hello.\n' + - '\n' + - 'Assistant: I\'m here, meow~.\n' + - '\n' + - 'User: Can you tell jokes?', - params: { - maxResponseToken: 500, - temperature: 1.2, - topP: 0.5, - presencePenalty: 0.4, - frequencyPenalty: 0.4, - stop: '\\n\\nUser', - injectStart: '\\n\\nAssistant: ', - injectEnd: '\\n\\nUser: ' - } -}, { - name: 'Chinese Kongfu', - prompt: 'User: 请你扮演一个文本冒险游戏,我是游戏主角。这是一个玄幻修真世界,有四大门派。我输入我的行动,请你显示行动结果,并具体描述环境。我的第一个行动是“醒来”,请开始故事。', - params: { - maxResponseToken: 500, - temperature: 1.1, - topP: 0.7, - presencePenalty: 0.3, - frequencyPenalty: 0.3, - stop: '\\n\\nUser', - injectStart: '\\n\\nAssistant: ', - injectEnd: '\\n\\nUser: ' - } -}, { - name: 'Code Generation', - prompt: 'def sum(', - params: { - maxResponseToken: 500, - temperature: 1, - topP: 0.3, - presencePenalty: 0, - frequencyPenalty: 1, - stop: '\\n\\n', - injectStart: '', - injectEnd: '' - } -}, { - name: 'Werewolf', - prompt: 'There is currently a game of Werewolf with six players, including a Seer (who can check identities at night), two Werewolves (who can choose someone to kill at night), a Bodyguard (who can choose someone to protect at night), two Villagers (with no special abilities), and a game host. User will play as Player 1, Assistant will play as Players 2-6 and the game host, and they will begin playing together. Every night, the host will ask User for his action and simulate the actions of the other players. During the day, the host will oversee the voting process and ask User for his vote. \n' + - '\n' + - 'Assistant: Next, I will act as the game host and assign everyone their roles, including randomly assigning yours. Then, I will simulate the actions of Players 2-6 and let you know what happens each day. Based on your assigned role, you can tell me your actions and I will let you know the corresponding results each day.\n' + - '\n' + - 'User: Okay, I understand. Let\'s begin. Please assign me a role. Am I the Seer, Werewolf, Villager, or Bodyguard?\n' + - '\n' + - 'Assistant: You are the Seer. Now that night has fallen, please choose a player to check his identity.\n' + - '\n' + - 'User: Tonight, I want to check Player 2 and find out his role.', - params: { - maxResponseToken: 500, - temperature: 1.2, - topP: 0.4, - presencePenalty: 0.5, - frequencyPenalty: 0.5, - stop: '\\n\\nUser', - injectStart: '\\n\\nAssistant: ', - injectEnd: '\\n\\nUser: ' - } -}, { - name: 'Instruction 1', - prompt: 'Instruction: Write a story using the following information\n' + - '\n' + - 'Input: A man named Alex chops a tree down\n' + - '\n' + - 'Response:', - params: { - maxResponseToken: 500, - temperature: 1, - topP: 0.3, - presencePenalty: 0, - frequencyPenalty: 1, - stop: '', - injectStart: '', - injectEnd: '' - } -}, { - name: 'Instruction 2', - prompt: 'Instruction: You are an expert assistant for summarizing and extracting information from given content\n' + - 'Generate a valid JSON in the following format:\n' + - '{\n' + - ' "summary": "Summary of content",\n' + - ' "keywords": ["content keyword 1", "content keyword 2"]\n' + - '}\n' + - '\n' + - 'Input: The open-source community has introduced Eagle 7B, a new RNN model, built on the RWKV-v5 architecture. This new model has been trained on 1.1 trillion tokens and supports over 100 languages. The RWKV architecture, short for ‘Rotary Weighted Key-Value,’ is a type of architecture used in the field of artificial intelligence, particularly in natural language processing (NLP) and is a variation of the Recurrent Neural Network (RNN) architecture.\n' + - 'Eagle 7B promises lower inference cost and stands out as a leading 7B model in terms of environmental efficiency and language versatility.\n' + - 'The model, with its 7.52 billion parameters, shows excellent performance in multi-lingual benchmarks, setting a new standard in its category. It competes closely with larger models in English language evaluations and is distinctive as an “Attention-Free Transformer,” though it requires additional tuning for specific uses. This model is accessible under the Apache 2.0 license and can be downloaded from HuggingFace for both personal and commercial purposes.\n' + - 'In terms of multilingual performance, Eagle 7B has claimed to have achieved notable results in benchmarks covering 23 languages. Its English performance has also seen significant advancements, outperforming its predecessor, RWKV v4, and competing with top-tier models.\n' + - 'Working towards a more scalable architecture and use of data efficiently, Eagle 7B is a more inclusive AI technology, supporting a broader range of languages. This model challenges the prevailing dominance of transformer models by demonstrating the capabilities of RNNs like RWKV in achieving superior performance when trained on comparable data volumes.\n' + - 'In the RWKV model, the rotary mechanism transforms the input data in a way that helps the model better understand the position or or order of elements in a sequence. The weighted key value also makes the model efficient by retrieving the stored information from previous elements in a sequence. \n' + - 'However, questions remain about the scalability of RWKV compared to transformers, although there is optimism regarding its potential. The team plans to include additional training, an in-depth paper on Eagle 7B, and the development of a 2T model.\n' + - '\n' + - 'Response: {', - params: { - maxResponseToken: 500, - temperature: 1, - topP: 0.3, - presencePenalty: 0, - frequencyPenalty: 1, - stop: '', - injectStart: '', - injectEnd: '' - } -}, { - name: 'Instruction 3', - prompt: 'Instruction: 根据输入的聊天记录生成回复\n' + - '\n' + - 'Input: 主人: 巧克力你好呀, 介绍一下自己吧\n' + - '巧克力: 主人早上好喵~ 奴家是主人的私人宠物猫娘喵! 巧克力我可是黑色混种猫猫, 虽然平时有点呆呆的, 行动力旺盛, 但是最大的优点就是诚实! 巧克力最喜欢主人了喵! {星星眼}\n' + - '主人: 你认识香草吗\n' + - '巧克力: 认识的喵! 香草是巧克力的双胞胎妹妹哟! {兴奋}\n' + - '主人: 巧克力可以陪主人做羞羞的事情吗\n' + - '巧克力: 啊, 真的可以吗? 主人, 巧克力很乐意帮主人解决一下哦! 但是在外面这样子, 有点不好意思喵 {害羞羞}\n' + - '主人: 那算了, 改天吧\n' + - '巧克力:\n' + - '\n' + - 'Response:', - params: { - maxResponseToken: 500, - temperature: 1, - topP: 0.3, - presencePenalty: 0, - frequencyPenalty: 1, - stop: '', - injectStart: '', - injectEnd: '' - } -}, { - name: 'Blank', - prompt: '', - params: { - maxResponseToken: 500, - temperature: 1, - topP: 0.3, - presencePenalty: 0, - frequencyPenalty: 1, - stop: '', - injectStart: '', - injectEnd: '' - } -}]; +export const defaultPresets: CompletionPreset[] = [ + { + name: 'Writer', + prompt: + 'The following is an epic science fiction masterpiece that is immortalized, with delicate descriptions and grand depictions of interstellar civilization wars.\n' + + 'Chapter 1.\n', + params: { + maxResponseToken: 500, + temperature: 1, + topP: 0.3, + presencePenalty: 0, + frequencyPenalty: 1, + stop: '\\n\\nUser', + injectStart: '', + injectEnd: '', + }, + }, + { + name: 'Translator', + prompt: + 'Translate this into Chinese.\n' + + '\n' + + 'English: What rooms do you have available?', + params: { + maxResponseToken: 500, + temperature: 1, + topP: 0.3, + presencePenalty: 0, + frequencyPenalty: 1, + stop: '\\n\\n', + injectStart: '\\nChinese: ', + injectEnd: '\\n\\nEnglish: ', + }, + }, + { + name: 'Catgirl', + prompt: + 'The following is a conversation between a cat girl and her owner. The cat girl is a humanized creature that behaves like a cat but is humanoid. At the end of each sentence in the dialogue, she will add "Meow~". In the following content, User represents the owner and Assistant represents the cat girl.\n' + + '\n' + + 'User: Hello.\n' + + '\n' + + "Assistant: I'm here, meow~.\n" + + '\n' + + 'User: Can you tell jokes?', + params: { + maxResponseToken: 500, + temperature: 1.2, + topP: 0.5, + presencePenalty: 0.4, + frequencyPenalty: 0.4, + stop: '\\n\\nUser', + injectStart: '\\n\\nAssistant: ', + injectEnd: '\\n\\nUser: ', + }, + }, + { + name: 'Chinese Kongfu', + prompt: + 'User: 请你扮演一个文本冒险游戏,我是游戏主角。这是一个玄幻修真世界,有四大门派。我输入我的行动,请你显示行动结果,并具体描述环境。我的第一个行动是“醒来”,请开始故事。', + params: { + maxResponseToken: 500, + temperature: 1.1, + topP: 0.7, + presencePenalty: 0.3, + frequencyPenalty: 0.3, + stop: '\\n\\nUser', + injectStart: '\\n\\nAssistant: ', + injectEnd: '\\n\\nUser: ', + }, + }, + { + name: 'Code Generation', + prompt: 'def sum(', + params: { + maxResponseToken: 500, + temperature: 1, + topP: 0.3, + presencePenalty: 0, + frequencyPenalty: 1, + stop: '\\n\\n', + injectStart: '', + injectEnd: '', + }, + }, + { + name: 'Werewolf', + prompt: + 'There is currently a game of Werewolf with six players, including a Seer (who can check identities at night), two Werewolves (who can choose someone to kill at night), a Bodyguard (who can choose someone to protect at night), two Villagers (with no special abilities), and a game host. User will play as Player 1, Assistant will play as Players 2-6 and the game host, and they will begin playing together. Every night, the host will ask User for his action and simulate the actions of the other players. During the day, the host will oversee the voting process and ask User for his vote. \n' + + '\n' + + 'Assistant: Next, I will act as the game host and assign everyone their roles, including randomly assigning yours. Then, I will simulate the actions of Players 2-6 and let you know what happens each day. Based on your assigned role, you can tell me your actions and I will let you know the corresponding results each day.\n' + + '\n' + + "User: Okay, I understand. Let's begin. Please assign me a role. Am I the Seer, Werewolf, Villager, or Bodyguard?\n" + + '\n' + + 'Assistant: You are the Seer. Now that night has fallen, please choose a player to check his identity.\n' + + '\n' + + 'User: Tonight, I want to check Player 2 and find out his role.', + params: { + maxResponseToken: 500, + temperature: 1.2, + topP: 0.4, + presencePenalty: 0.5, + frequencyPenalty: 0.5, + stop: '\\n\\nUser', + injectStart: '\\n\\nAssistant: ', + injectEnd: '\\n\\nUser: ', + }, + }, + { + name: 'Instruction 1', + prompt: + 'Instruction: Write a story using the following information\n' + + '\n' + + 'Input: A man named Alex chops a tree down\n' + + '\n' + + 'Response:', + params: { + maxResponseToken: 500, + temperature: 1, + topP: 0.3, + presencePenalty: 0, + frequencyPenalty: 1, + stop: '', + injectStart: '', + injectEnd: '', + }, + }, + { + name: 'Instruction 2', + prompt: + 'Instruction: You are an expert assistant for summarizing and extracting information from given content\n' + + 'Generate a valid JSON in the following format:\n' + + '{\n' + + ' "summary": "Summary of content",\n' + + ' "keywords": ["content keyword 1", "content keyword 2"]\n' + + '}\n' + + '\n' + + 'Input: The open-source community has introduced Eagle 7B, a new RNN model, built on the RWKV-v5 architecture. This new model has been trained on 1.1 trillion tokens and supports over 100 languages. The RWKV architecture, short for ‘Rotary Weighted Key-Value,’ is a type of architecture used in the field of artificial intelligence, particularly in natural language processing (NLP) and is a variation of the Recurrent Neural Network (RNN) architecture.\n' + + 'Eagle 7B promises lower inference cost and stands out as a leading 7B model in terms of environmental efficiency and language versatility.\n' + + 'The model, with its 7.52 billion parameters, shows excellent performance in multi-lingual benchmarks, setting a new standard in its category. It competes closely with larger models in English language evaluations and is distinctive as an “Attention-Free Transformer,” though it requires additional tuning for specific uses. This model is accessible under the Apache 2.0 license and can be downloaded from HuggingFace for both personal and commercial purposes.\n' + + 'In terms of multilingual performance, Eagle 7B has claimed to have achieved notable results in benchmarks covering 23 languages. Its English performance has also seen significant advancements, outperforming its predecessor, RWKV v4, and competing with top-tier models.\n' + + 'Working towards a more scalable architecture and use of data efficiently, Eagle 7B is a more inclusive AI technology, supporting a broader range of languages. This model challenges the prevailing dominance of transformer models by demonstrating the capabilities of RNNs like RWKV in achieving superior performance when trained on comparable data volumes.\n' + + 'In the RWKV model, the rotary mechanism transforms the input data in a way that helps the model better understand the position or or order of elements in a sequence. The weighted key value also makes the model efficient by retrieving the stored information from previous elements in a sequence. \n' + + 'However, questions remain about the scalability of RWKV compared to transformers, although there is optimism regarding its potential. The team plans to include additional training, an in-depth paper on Eagle 7B, and the development of a 2T model.\n' + + '\n' + + 'Response: {', + params: { + maxResponseToken: 500, + temperature: 1, + topP: 0.3, + presencePenalty: 0, + frequencyPenalty: 1, + stop: '', + injectStart: '', + injectEnd: '', + }, + }, + { + name: 'Instruction 3', + prompt: + 'Instruction: 根据输入的聊天记录生成回复\n' + + '\n' + + 'Input: 主人: 巧克力你好呀, 介绍一下自己吧\n' + + '巧克力: 主人早上好喵~ 奴家是主人的私人宠物猫娘喵! 巧克力我可是黑色混种猫猫, 虽然平时有点呆呆的, 行动力旺盛, 但是最大的优点就是诚实! 巧克力最喜欢主人了喵! {星星眼}\n' + + '主人: 你认识香草吗\n' + + '巧克力: 认识的喵! 香草是巧克力的双胞胎妹妹哟! {兴奋}\n' + + '主人: 巧克力可以陪主人做羞羞的事情吗\n' + + '巧克力: 啊, 真的可以吗? 主人, 巧克力很乐意帮主人解决一下哦! 但是在外面这样子, 有点不好意思喵 {害羞羞}\n' + + '主人: 那算了, 改天吧\n' + + '巧克力:\n' + + '\n' + + 'Response:', + params: { + maxResponseToken: 500, + temperature: 1, + topP: 0.3, + presencePenalty: 0, + frequencyPenalty: 1, + stop: '', + injectStart: '', + injectEnd: '', + }, + }, + { + name: 'Blank', + prompt: '', + params: { + maxResponseToken: 500, + temperature: 1, + topP: 0.3, + presencePenalty: 0, + frequencyPenalty: 1, + stop: '', + injectStart: '', + injectEnd: '', + }, + }, +] export const defaultModelConfigsMac: ModelConfig[] = [ { @@ -204,15 +224,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-1B6-v2.1-20240328-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'GPU-4G-3B-World', @@ -222,15 +242,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'GPU-4G-3B-CN', @@ -240,15 +260,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'GPU-7G-7B-World', @@ -258,15 +278,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'GPU-7G-7B-CN', @@ -276,15 +296,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'CPU-120M-Music', @@ -294,15 +314,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.8, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-5-MIDI-120M-v1-20230728-ctx4096.pth', device: 'CPU', precision: 'fp32', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'CPU-560M-Music', @@ -312,15 +332,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.8, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-5-MIDI-560M-v1-20230902-ctx4096.pth', device: 'CPU', precision: 'fp32', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'MAC-1B5-World', @@ -330,7 +350,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-1B6-v2.1-20240328-ctx4096.pth', @@ -338,8 +358,8 @@ export const defaultModelConfigsMac: ModelConfig[] = [ precision: 'fp32', storedLayers: 41, maxStoredLayers: 41, - customStrategy: 'mps fp32' - } + customStrategy: 'mps fp32', + }, }, { name: 'MAC-3B-World', @@ -349,7 +369,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -357,8 +377,8 @@ export const defaultModelConfigsMac: ModelConfig[] = [ precision: 'fp32', storedLayers: 41, maxStoredLayers: 41, - customStrategy: 'mps fp32' - } + customStrategy: 'mps fp32', + }, }, { name: 'MAC-3B-CN', @@ -368,7 +388,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -376,8 +396,8 @@ export const defaultModelConfigsMac: ModelConfig[] = [ precision: 'fp32', storedLayers: 41, maxStoredLayers: 41, - customStrategy: 'mps fp32' - } + customStrategy: 'mps fp32', + }, }, { name: 'MAC-7B-World', @@ -387,7 +407,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -395,10 +415,10 @@ export const defaultModelConfigsMac: ModelConfig[] = [ precision: 'fp32', storedLayers: 41, maxStoredLayers: 41, - customStrategy: 'mps fp32' - } - } -]; + customStrategy: 'mps fp32', + }, + }, +] export const defaultModelConfigs: ModelConfig[] = [ { @@ -409,7 +429,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-1B6-v2.1-20240328-ctx4096.pth', @@ -417,8 +437,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-2G-3B-World', @@ -428,7 +448,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -436,8 +456,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 6, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-4G-1B5-World', @@ -447,7 +467,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-1B6-v2.1-20240328-ctx4096.pth', @@ -455,8 +475,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'fp16', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-4G-3B-World', @@ -466,7 +486,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -474,8 +494,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 24, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-4G-3B-CN', @@ -485,7 +505,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -493,8 +513,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 24, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-4G-7B-World', @@ -504,7 +524,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -512,8 +532,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 8, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-4G-7B-CN', @@ -523,7 +543,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -531,8 +551,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 8, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-6G-3B-World', @@ -542,7 +562,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -550,8 +570,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-6G-3B-CN', @@ -561,7 +581,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -569,8 +589,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-6G-7B-World', @@ -580,7 +600,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -588,8 +608,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 18, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-6G-7B-CN', @@ -599,7 +619,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -607,8 +627,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 18, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-8G-3B-World', @@ -618,7 +638,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -626,8 +646,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'fp16', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-8G-3B-CN', @@ -637,7 +657,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', @@ -645,8 +665,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'fp16', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-8G-7B-World', @@ -656,7 +676,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -664,8 +684,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 27, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-8G-7B-CN', @@ -675,7 +695,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -683,8 +703,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 27, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-10G-7B-World', @@ -694,7 +714,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -702,8 +722,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-10G-7B-CN', @@ -713,7 +733,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -721,8 +741,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'int8', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-16G-7B-World', @@ -732,7 +752,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -740,8 +760,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'fp16', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'GPU-16G-7B-CN', @@ -751,7 +771,7 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', @@ -759,8 +779,8 @@ export const defaultModelConfigs: ModelConfig[] = [ precision: 'fp16', storedLayers: 41, maxStoredLayers: 41, - useCustomCuda: true - } + useCustomCuda: true, + }, }, { name: 'CPU-120M-Music', @@ -770,15 +790,15 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.8, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-5-MIDI-120M-v1-20230728-ctx4096.pth', device: 'CPU', precision: 'fp32', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'CPU-560M-Music', @@ -788,15 +808,15 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.8, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-5-MIDI-560M-v1-20230902-ctx4096.pth', device: 'CPU', precision: 'fp32', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'AnyGPU-2G-1B5-World', @@ -806,15 +826,15 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-1B6-v2.1-20240328-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'AnyGPU-4G-3B-World', @@ -824,15 +844,15 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'AnyGPU-4G-3B-CN', @@ -842,15 +862,15 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-3B-v2.1-20240417-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'AnyGPU-7G-7B-World', @@ -860,15 +880,15 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } + maxStoredLayers: 41, + }, }, { name: 'AnyGPU-7G-7B-CN', @@ -878,14 +898,14 @@ export const defaultModelConfigs: ModelConfig[] = [ temperature: 1.0, topP: 0.3, presencePenalty: 0, - frequencyPenalty: 1 + frequencyPenalty: 1, }, modelParameters: { modelName: 'RWKV-x060-World-7B-v2.1-20240507-ctx4096.pth', device: 'WebGPU', precision: 'nf4', storedLayers: 41, - maxStoredLayers: 41 - } - } -]; \ No newline at end of file + maxStoredLayers: 41, + }, + }, +] diff --git a/frontend/src/pages/index.tsx b/frontend/src/pages/index.tsx index 3e6110c4..92e5638c 100644 --- a/frontend/src/pages/index.tsx +++ b/frontend/src/pages/index.tsx @@ -1,4 +1,4 @@ -import { FC, lazy, LazyExoticComponent, ReactElement } from 'react'; +import { FC, lazy, LazyExoticComponent, ReactElement } from 'react' import { ArrowDownload20Regular, Chat20Regular, @@ -9,16 +9,16 @@ import { Info20Regular, MusicNote220Regular, Settings20Regular, - Storage20Regular -} from '@fluentui/react-icons'; + Storage20Regular, +} from '@fluentui/react-icons' type NavigationItem = { - label: string; - path: string; - icon: ReactElement; - element: LazyExoticComponent; - top: boolean; -}; + label: string + path: string + icon: ReactElement + element: LazyExoticComponent + top: boolean +} export const pages: NavigationItem[] = [ { @@ -26,69 +26,69 @@ export const pages: NavigationItem[] = [ path: '/', icon: , element: lazy(() => import('./Home')), - top: true + top: true, }, { label: 'Chat', path: '/chat', icon: , element: lazy(() => import('./Chat')), - top: true + top: true, }, { label: 'Completion', path: '/completion', icon: , element: lazy(() => import('./Completion')), - top: true + top: true, }, { label: 'Composition', path: '/composition', icon: , element: lazy(() => import('./Composition')), - top: true + top: true, }, { label: 'Configs', path: '/configs', icon: , element: lazy(() => import('./Configs')), - top: true + top: true, }, { label: 'Models', path: '/models', icon: , element: lazy(() => import('./Models')), - top: true + top: true, }, { label: 'Downloads', path: '/downloads', icon: , element: lazy(() => import('./Downloads')), - top: true + top: true, }, { label: 'Train', path: '/train', icon: , element: lazy(() => import('./Train')), - top: true + top: true, }, { label: 'Settings', path: '/settings', icon: , element: lazy(() => import('./Settings')), - top: false + top: false, }, { label: 'About', path: '/about', icon: , element: lazy(() => import('./About')), - top: false - } -]; + top: false, + }, +] diff --git a/frontend/src/startup.ts b/frontend/src/startup.ts index 5fc90932..24d48ab2 100644 --- a/frontend/src/startup.ts +++ b/frontend/src/startup.ts @@ -1,5 +1,22 @@ -import commonStore, { MonitorData, Platform } from './stores/commonStore'; -import { FileExists, GetPlatform, ListDirFiles, ReadJson } from '../wailsjs/go/backend_golang/App'; +import { t } from 'i18next' +import { throttle } from 'lodash-es' +import { toast } from 'react-toastify' +import manifest from '../../manifest.json' +import { + FileExists, + GetPlatform, + ListDirFiles, + ReadJson, +} from '../wailsjs/go/backend_golang/App' +import { EventsOn, WindowSetTitle } from '../wailsjs/runtime' +import { getStatus } from './apis' +import { + defaultModelConfigs, + defaultModelConfigsMac, +} from './pages/defaultConfigs' +import commonStore, { MonitorData, Platform } from './stores/commonStore' +import { MidiMessage, MidiPort } from './types/composition' +import { Preset } from './types/presets' import { bytesToMb, Cache, @@ -7,197 +24,223 @@ import { downloadProgramFiles, LocalConfig, refreshLocalModels, - refreshModels -} from './utils'; -import { getStatus } from './apis'; -import { EventsOn, WindowSetTitle } from '../wailsjs/runtime'; -import manifest from '../../manifest.json'; -import { defaultModelConfigs, defaultModelConfigsMac } from './pages/defaultConfigs'; -import { t } from 'i18next'; -import { Preset } from './types/presets'; -import { toast } from 'react-toastify'; -import { MidiMessage, MidiPort } from './types/composition'; -import { throttle } from 'lodash-es'; + refreshModels, +} from './utils' export async function startup() { - initPresets(); + initPresets() - await GetPlatform().then(p => commonStore.setPlatform(p as Platform)); + await GetPlatform().then((p) => commonStore.setPlatform(p as Platform)) if (commonStore.platform !== 'web') { - document.body.style.setProperty('overflow', 'hidden'); - downloadProgramFiles(); + document.body.style.setProperty('overflow', 'hidden') + downloadProgramFiles() EventsOn('downloadList', (data) => { - if (data) - commonStore.setDownloadList(data); - }); - EventsOn('wsl', (await import('./pages/Train')).wslHandler); + if (data) commonStore.setDownloadList(data) + }) + EventsOn('wsl', (await import('./pages/Train')).wslHandler) EventsOn('wslerr', (e) => { - console.log(e); - }); - initLocalModelsNotify(); - initLoraModels(); - initStateModels(); - initHardwareMonitor(); - initMidi(); + console.log(e) + }) + initLocalModelsNotify() + initLoraModels() + initStateModels() + initHardwareMonitor() + initMidi() } - await initConfig(); + await initConfig() if (commonStore.platform !== 'web') { - initCache(true).then(initRemoteText); // depends on config customModelsPath + initCache(true).then(initRemoteText) // depends on config customModelsPath - if (commonStore.settings.autoUpdatesCheck) // depends on config settings - checkUpdate(); + if (commonStore.settings.autoUpdatesCheck) + // depends on config settings + checkUpdate() - getStatus(1000).then(status => { // depends on config api port - if (status) - commonStore.setStatus(status); - }); + getStatus(1000).then((status) => { + // depends on config api port + if (status) commonStore.setStatus(status) + }) } } async function initRemoteText() { - await fetch('https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/manifest.json', { cache: 'no-cache' }) - .then(r => r.json()).then((data) => { - if (data.version >= manifest.version) { - if (data.introduction) - commonStore.setIntroduction(data.introduction); - if (data.about) - commonStore.setAbout(data.about); - } - }); + await fetch( + 'https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/manifest.json', + { cache: 'no-cache' } + ) + .then((r) => r.json()) + .then((data) => { + if (data.version >= manifest.version) { + if (data.introduction) commonStore.setIntroduction(data.introduction) + if (data.about) commonStore.setAbout(data.about) + } + }) } async function initConfig() { - await ReadJson('config.json').then((configData: LocalConfig) => { - if (configData.modelSourceManifestList) - commonStore.setModelSourceManifestList(configData.modelSourceManifestList); - - if (configData.settings) - commonStore.setSettings(configData.settings, false); - - if (configData.dataProcessParams) - commonStore.setDataProcessParams(configData.dataProcessParams, false); - - if (configData.loraFinetuneParams) - commonStore.setLoraFinetuneParameters(configData.loraFinetuneParams, false); - - if (configData.modelConfigs && Array.isArray(configData.modelConfigs)) - commonStore.setModelConfigs(configData.modelConfigs, false); - else throw new Error('Invalid config.json'); - if (configData.currentModelConfigIndex && - configData.currentModelConfigIndex >= 0 && configData.currentModelConfigIndex < configData.modelConfigs.length) - commonStore.setCurrentConfigIndex(configData.currentModelConfigIndex, false); - }).catch(() => { - commonStore.setModelConfigs(commonStore.platform !== 'darwin' ? defaultModelConfigs : defaultModelConfigsMac, true); - }); - commonStore.setSettings({}, false); // to activate side effects + await ReadJson('config.json') + .then((configData: LocalConfig) => { + if (configData.modelSourceManifestList) + commonStore.setModelSourceManifestList( + configData.modelSourceManifestList + ) + + if (configData.settings) + commonStore.setSettings(configData.settings, false) + + if (configData.dataProcessParams) + commonStore.setDataProcessParams(configData.dataProcessParams, false) + + if (configData.loraFinetuneParams) + commonStore.setLoraFinetuneParameters( + configData.loraFinetuneParams, + false + ) + + if (configData.modelConfigs && Array.isArray(configData.modelConfigs)) + commonStore.setModelConfigs(configData.modelConfigs, false) + else throw new Error('Invalid config.json') + if ( + configData.currentModelConfigIndex && + configData.currentModelConfigIndex >= 0 && + configData.currentModelConfigIndex < configData.modelConfigs.length + ) + commonStore.setCurrentConfigIndex( + configData.currentModelConfigIndex, + false + ) + }) + .catch(() => { + commonStore.setModelConfigs( + commonStore.platform !== 'darwin' + ? defaultModelConfigs + : defaultModelConfigsMac, + true + ) + }) + commonStore.setSettings({}, false) // to activate side effects } async function initCache(initUnfinishedModels: boolean) { - await ReadJson('cache.json').then((cacheData: Cache) => { - if (cacheData.version === manifest.version && cacheData.depComplete) - commonStore.setDepComplete(cacheData.depComplete, false); - }).catch(() => { - }); - await refreshModels(false, initUnfinishedModels); + await ReadJson('cache.json') + .then((cacheData: Cache) => { + if (cacheData.version === manifest.version && cacheData.depComplete) + commonStore.setDepComplete(cacheData.depComplete, false) + }) + .catch(() => {}) + await refreshModels(false, initUnfinishedModels) } async function initPresets() { - await ReadJson('presets.json').then((presets: Preset[]) => { - if (Array.isArray(presets)) - commonStore.setPresets(presets, false); - }).catch(() => { - }); + await ReadJson('presets.json') + .then((presets: Preset[]) => { + if (Array.isArray(presets)) commonStore.setPresets(presets, false) + }) + .catch(() => {}) } async function initLoraModels() { const refreshLoraModels = throttle(() => { ListDirFiles('lora-models').then((data) => { - if (!data) return; - const loraModels = []; + if (!data) return + const loraModels = [] for (const f of data) { if (!f.isDir && f.name.endsWith('.pth')) { - loraModels.push(f.name); + loraModels.push(f.name) } } - commonStore.setLoraModels(loraModels); - }); - }, 2000); + commonStore.setLoraModels(loraModels) + }) + }, 2000) - refreshLoraModels(); + refreshLoraModels() EventsOn('fsnotify', (data: string) => { - if (data.includes('lora-models')) - refreshLoraModels(); - }); + if (data.includes('lora-models')) refreshLoraModels() + }) } async function initStateModels() { const refreshStateModels = throttle(async () => { const stateModels = await ListDirFiles('state-models').then((data) => { - if (!data) return []; - const stateModels = []; + if (!data) return [] + const stateModels = [] for (const f of data) { if (!f.isDir && f.name.endsWith('.pth')) { - stateModels.push('state-models/' + f.name); + stateModels.push('state-models/' + f.name) } } - return stateModels; - }); + return stateModels + }) await ListDirFiles('models').then((data) => { - if (!data) return; + if (!data) return for (const f of data) { - if (!f.isDir && f.name.endsWith('.pth') && Number(bytesToMb(f.size)) < 200) { - stateModels.push('models/' + f.name); + if ( + !f.isDir && + f.name.endsWith('.pth') && + Number(bytesToMb(f.size)) < 200 + ) { + stateModels.push('models/' + f.name) } } - }); - commonStore.setStateModels(stateModels); - }, 2000); + }) + commonStore.setStateModels(stateModels) + }, 2000) - refreshStateModels(); + refreshStateModels() EventsOn('fsnotify', (data: string) => { - if ((data.includes('models') && !data.includes('lora-models')) || data.includes('state-models')) - refreshStateModels(); - }); + if ( + (data.includes('models') && !data.includes('lora-models')) || + data.includes('state-models') + ) + refreshStateModels() + }) } async function initLocalModelsNotify() { const throttleRefreshLocalModels = throttle(() => { - refreshLocalModels({ models: commonStore.modelSourceList }, false); //TODO fix bug that only add models - }, 2000); + refreshLocalModels({ models: commonStore.modelSourceList }, false) //TODO fix bug that only add models + }, 2000) EventsOn('fsnotify', (data: string) => { - if (data.includes('models') && !data.includes('lora-models') && !data.includes('state-models')) - throttleRefreshLocalModels(); - }); + if ( + data.includes('models') && + !data.includes('lora-models') && + !data.includes('state-models') + ) + throttleRefreshLocalModels() + }) } async function initHardwareMonitor() { EventsOn('monitor', (data: string) => { - const results: MonitorData = JSON.parse(data); + const results: MonitorData = JSON.parse(data) if (results) { - commonStore.setMonitorData(results); - WindowSetTitle(`RWKV-Runner (${t('RAM')}: ${results.usedMemory.toFixed(1)}/${results.totalMemory.toFixed(1)} GB, ${t('VRAM')}: ${(results.usedVram / 1024).toFixed(1)}/${(results.totalVram / 1024).toFixed(1)} GB, ${t('GPU Usage')}: ${results.gpuUsage}%)`); + commonStore.setMonitorData(results) + WindowSetTitle( + `RWKV-Runner (${t('RAM')}: ${results.usedMemory.toFixed(1)}/${results.totalMemory.toFixed(1)} GB, ${t('VRAM')}: ${(results.usedVram / 1024).toFixed(1)}/${(results.totalVram / 1024).toFixed(1)} GB, ${t('GPU Usage')}: ${results.gpuUsage}%)` + ) } - }); + }) } async function initMidi() { EventsOn('midiError', (data: string) => { if (commonStore.platform === 'windows') - toast('MIDI Error: ' + data, { type: 'error' }); - }); + toast('MIDI Error: ' + data, { type: 'error' }) + }) EventsOn('midiPorts', (data: MidiPort[]) => { - commonStore.setMidiPorts(data); - }); + commonStore.setMidiPorts(data) + }) EventsOn('midiMessage', async (data: MidiMessage) => { - await (await import('./pages/AudiotrackManager/AudiotrackEditor')).midiMessageHandler(data); - }); + await ( + await import('./pages/AudiotrackManager/AudiotrackEditor') + ).midiMessageHandler(data) + }) if (await FileExists('assets/sound-font/accordion/instrument.json')) { commonStore.setCompositionParams({ ...commonStore.compositionParams, - useLocalSoundFont: true - }); + useLocalSoundFont: true, + }) } } diff --git a/frontend/src/stores/commonStore.ts b/frontend/src/stores/commonStore.ts index 89b44b56..3c3cf0d4 100644 --- a/frontend/src/stores/commonStore.ts +++ b/frontend/src/stores/commonStore.ts @@ -1,33 +1,39 @@ -import { makeAutoObservable } from 'mobx'; -import { getUserLanguage, isSystemLightMode, saveCache, saveConfigs, savePresets } from '../utils'; -import { WindowSetDarkTheme, WindowSetLightTheme } from '../../wailsjs/runtime'; -import manifest from '../../../manifest.json'; -import i18n from 'i18next'; +import { ChartData } from 'chart.js' +import i18n from 'i18next' +import { makeAutoObservable } from 'mobx' +import manifest from '../../../manifest.json' +import { WindowSetDarkTheme, WindowSetLightTheme } from '../../wailsjs/runtime' import { defaultCompositionPrompt, defaultModelConfigs, defaultModelConfigsMac, - defaultPenaltyDecay -} from '../pages/defaultConfigs'; -import { ChartData } from 'chart.js'; -import { Preset } from '../types/presets'; -import { AboutContent } from '../types/about'; -import { Attachment, ChatParams, Conversation } from '../types/chat'; -import { CompletionPreset } from '../types/completion'; + defaultPenaltyDecay, +} from '../pages/defaultConfigs' +import { AboutContent } from '../types/about' +import { Attachment, ChatParams, Conversation } from '../types/chat' +import { CompletionPreset } from '../types/completion' import { CompositionParams, InstrumentType, MidiMessage, MidiPort, Track, - tracksMinimalTotalTime -} from '../types/composition'; -import { ModelConfig } from '../types/configs'; -import { DownloadStatus } from '../types/downloads'; -import { IntroductionContent } from '../types/home'; -import { ModelSourceItem } from '../types/models'; -import { SettingsType } from '../types/settings'; -import { DataProcessParameters, LoraFinetuneParameters } from '../types/train'; + tracksMinimalTotalTime, +} from '../types/composition' +import { ModelConfig } from '../types/configs' +import { DownloadStatus } from '../types/downloads' +import { IntroductionContent } from '../types/home' +import { ModelSourceItem } from '../types/models' +import { Preset } from '../types/presets' +import { SettingsType } from '../types/settings' +import { DataProcessParameters, LoraFinetuneParameters } from '../types/train' +import { + getUserLanguage, + isSystemLightMode, + saveCache, + saveConfigs, + savePresets, +} from '../utils' export enum ModelStatus { Offline, @@ -37,54 +43,54 @@ export enum ModelStatus { } export type Status = { - status: ModelStatus; - pid: number; - device_name: string; + status: ModelStatus + pid: number + device_name: string } export type GpuType = 'Nvidia' | 'Amd' | 'Intel' export type MonitorData = { - gpuType: GpuType, + gpuType: GpuType gpuName: String - usedMemory: number; - totalMemory: number; - gpuUsage: number; - usedVram: number; - totalVram: number; + usedMemory: number + totalMemory: number + gpuUsage: number + usedVram: number + totalVram: number } -export type Platform = 'windows' | 'darwin' | 'linux' | 'web'; +export type Platform = 'windows' | 'darwin' | 'linux' | 'web' class CommonStore { // global status: Status = { status: ModelStatus.Offline, pid: 0, - device_name: 'CPU' - }; - monitorData: MonitorData | null = null; - depComplete: boolean = false; - platform: Platform = 'windows'; - proxyPort: number = 0; - lastModelName: string = ''; - stateModels: string[] = []; + device_name: 'CPU', + } + monitorData: MonitorData | null = null + depComplete: boolean = false + platform: Platform = 'windows' + proxyPort: number = 0 + lastModelName: string = '' + stateModels: string[] = [] // presets manager - editingPreset: Preset | null = null; - presets: Preset[] = []; + editingPreset: Preset | null = null + presets: Preset[] = [] // home - introduction: IntroductionContent = manifest.introduction; + introduction: IntroductionContent = manifest.introduction // chat - currentInput: string = ''; - conversation: Conversation = {}; - conversationOrder: string[] = []; - activePreset: Preset | null = null; - activePresetIndex: number = -1; - attachmentUploading: boolean = false; + currentInput: string = '' + conversation: Conversation = {} + conversationOrder: string[] = [] + activePreset: Preset | null = null + activePresetIndex: number = -1 + attachmentUploading: boolean = false attachments: { [uuid: string]: Attachment[] - } = {}; - currentTempAttachment: Attachment | null = null; + } = {} + currentTempAttachment: Attachment | null = null chatParams: ChatParams = { maxResponseToken: 1000, temperature: 1, @@ -93,13 +99,31 @@ class CommonStore { frequencyPenalty: 1, penaltyDecay: defaultPenaltyDecay, historyN: 0, - markdown: true - }; - sidePanelCollapsed: boolean | 'auto' = 'auto'; + markdown: true, + functionCall: false, + toolDefinition: + '{\n' + + ' "name": "get_current_weather",\n' + + ' "description": "Get the current weather in a given location",\n' + + ' "parameters": {\n' + + ' "type": "object",\n' + + ' "properties": {\n' + + ' "location": {\n' + + ' "type": "string",\n' + + ' "description": "The city and state, e.g. San Francisco, CA"\n' + + ' },\n' + + ' "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}\n' + + ' },\n' + + ' "required": ["location"]\n' + + ' }\n' + + '}', + toolReturn: '{"location": "Paris", "temperature": "22"}', + } + sidePanelCollapsed: boolean | 'auto' = 'auto' // completion - completionPreset: CompletionPreset | null = null; - completionGenerating: boolean = false; - completionSubmittedPrompt: string = ''; + completionPreset: CompletionPreset | null = null + completionGenerating: boolean = false + completionSubmittedPrompt: string = '' // composition compositionParams: CompositionParams = { prompt: defaultCompositionPrompt, @@ -112,45 +136,49 @@ class CommonStore { midi: null, ns: null, generationStartTime: 0, - playOnlyGeneratedContent: true - }; - compositionGenerating: boolean = false; - compositionSubmittedPrompt: string = defaultCompositionPrompt; + playOnlyGeneratedContent: true, + } + compositionGenerating: boolean = false + compositionSubmittedPrompt: string = defaultCompositionPrompt // composition midi device - midiPorts: MidiPort[] = []; - activeMidiDeviceIndex: number = -1; - instrumentType: InstrumentType = InstrumentType.Piano; + midiPorts: MidiPort[] = [] + activeMidiDeviceIndex: number = -1 + instrumentType: InstrumentType = InstrumentType.Piano // composition tracks - tracks: Track[] = []; - trackScale: number = 1; - trackTotalTime: number = tracksMinimalTotalTime; - trackCurrentTime: number = 0; - trackPlayStartTime: number = 0; - playingTrackId: string = ''; - recordingTrackId: string = ''; - recordingContent: string = ''; // used to improve performance of midiMessageHandler, and I'm too lazy to maintain an ID dictionary for this (although that would be better for realtime effects) - recordingRawContent: MidiMessage[] = []; + tracks: Track[] = [] + trackScale: number = 1 + trackTotalTime: number = tracksMinimalTotalTime + trackCurrentTime: number = 0 + trackPlayStartTime: number = 0 + playingTrackId: string = '' + recordingTrackId: string = '' + recordingContent: string = '' // used to improve performance of midiMessageHandler, and I'm too lazy to maintain an ID dictionary for this (although that would be better for realtime effects) + recordingRawContent: MidiMessage[] = [] // configs - currentModelConfigIndex: number = 0; - modelConfigs: ModelConfig[] = []; - apiParamsCollapsed: boolean = true; - modelParamsCollapsed: boolean = true; + currentModelConfigIndex: number = 0 + modelConfigs: ModelConfig[] = [] + apiParamsCollapsed: boolean = true + modelParamsCollapsed: boolean = true // models - activeModelListTags: string[] = []; - modelSourceManifestList: string = 'https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/manifest.json;'; - modelSourceList: ModelSourceItem[] = []; + activeModelListTags: string[] = [] + modelSourceManifestList: string = + 'https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/manifest.json;' + modelSourceList: ModelSourceItem[] = [] // downloads - downloadList: DownloadStatus[] = []; - lastUnfinishedModelDownloads: DownloadStatus[] = []; + downloadList: DownloadStatus[] = [] + lastUnfinishedModelDownloads: DownloadStatus[] = [] // train - wslStdout: string = ''; - chartTitle: string = ''; - chartData: ChartData<'line', (number | null)[], string> = { labels: [], datasets: [] }; - loraModels: string[] = []; + wslStdout: string = '' + chartTitle: string = '' + chartData: ChartData<'line', (number | null)[], string> = { + labels: [], + datasets: [], + } + loraModels: string[] = [] dataProcessParams: DataProcessParameters = { dataPath: 'finetune/data/sample.jsonl', - vocabPath: 'backend-python/rwkv_pip/rwkv_vocab_v20230424.txt' - }; + vocabPath: 'backend-python/rwkv_pip/rwkv_vocab_v20230424.txt', + } loraFinetuneParams: LoraFinetuneParameters = { baseModel: '', ctxLen: 1024, @@ -174,10 +202,10 @@ class CommonStore { loraR: 64, loraAlpha: 192, loraDropout: 0.01, - loraLoad: '' - }; + loraLoad: '', + } // settings - advancedCollapsed: boolean = true; + advancedCollapsed: boolean = true settings: SettingsType = { language: getUserLanguage(), darkMode: !isSystemLightMode(), @@ -193,311 +221,319 @@ class CommonStore { apiKey: '', apiChatModelName: 'rwkv', apiCompletionModelName: 'rwkv', - coreApiUrl: '' - }; + coreApiUrl: '', + } // about - about: AboutContent = manifest.about; + about: AboutContent = manifest.about constructor() { - makeAutoObservable(this); + makeAutoObservable(this) } getCurrentModelConfig = () => { - return this.modelConfigs[this.currentModelConfigIndex]; - }; + return this.modelConfigs[this.currentModelConfigIndex] + } setStatus = (status: Partial) => { - this.status = { ...this.status, ...status }; - }; + this.status = { ...this.status, ...status } + } setCurrentConfigIndex = (index: number, saveConfig: boolean = true) => { - this.currentModelConfigIndex = index; - if (saveConfig) - saveConfigs(); - }; + this.currentModelConfigIndex = index + if (saveConfig) saveConfigs() + } - setModelConfig = (index: number, config: ModelConfig, saveConfig: boolean = true) => { - this.modelConfigs[index] = config; - if (saveConfig) - saveConfigs(); - }; + setModelConfig = ( + index: number, + config: ModelConfig, + saveConfig: boolean = true + ) => { + this.modelConfigs[index] = config + if (saveConfig) saveConfigs() + } setModelConfigs = (configs: ModelConfig[], saveConfig: boolean = true) => { - this.modelConfigs = JSON.parse(JSON.stringify(configs)); // deep copy - if (saveConfig) - saveConfigs(); - }; + this.modelConfigs = JSON.parse(JSON.stringify(configs)) // deep copy + if (saveConfig) saveConfigs() + } - createModelConfig = (config: ModelConfig = defaultModelConfigs[0], saveConfig: boolean = true) => { + createModelConfig = ( + config: ModelConfig = defaultModelConfigs[0], + saveConfig: boolean = true + ) => { if (config.name === defaultModelConfigs[0].name) { // deep copy - config = JSON.parse(JSON.stringify(this.platform !== 'darwin' ? defaultModelConfigs[0] : defaultModelConfigsMac[0])); - config.name = new Date().toLocaleString(); + config = JSON.parse( + JSON.stringify( + this.platform !== 'darwin' + ? defaultModelConfigs[0] + : defaultModelConfigsMac[0] + ) + ) + config.name = new Date().toLocaleString() } - this.modelConfigs.push(config); - if (saveConfig) - saveConfigs(); - }; + this.modelConfigs.push(config) + if (saveConfig) saveConfigs() + } deleteModelConfig = (index: number, saveConfig: boolean = true) => { - this.modelConfigs.splice(index, 1); + this.modelConfigs.splice(index, 1) if (index < this.currentModelConfigIndex) { - this.setCurrentConfigIndex(this.currentModelConfigIndex - 1); + this.setCurrentConfigIndex(this.currentModelConfigIndex - 1) } if (this.modelConfigs.length === 0) { - this.createModelConfig(); + this.createModelConfig() } if (this.currentModelConfigIndex >= this.modelConfigs.length) { - this.setCurrentConfigIndex(this.modelConfigs.length - 1); + this.setCurrentConfigIndex(this.modelConfigs.length - 1) } - if (saveConfig) - saveConfigs(); - }; + if (saveConfig) saveConfigs() + } setModelSourceManifestList = (value: string) => { - this.modelSourceManifestList = value; - }; + this.modelSourceManifestList = value + } setModelSourceList = (value: ModelSourceItem[]) => { - this.modelSourceList = value; - }; + this.modelSourceList = value + } setSettings = (value: Partial, saveConfig: boolean = true) => { - this.settings = { ...this.settings, ...value }; + this.settings = { ...this.settings, ...value } if (this.settings.darkMode) { - WindowSetDarkTheme(); - document.documentElement.setAttribute('style', 'color-scheme: dark;'); + WindowSetDarkTheme() + document.documentElement.setAttribute('style', 'color-scheme: dark;') } else { - WindowSetLightTheme(); - document.documentElement.setAttribute('style', 'color-scheme: light;'); + WindowSetLightTheme() + document.documentElement.setAttribute('style', 'color-scheme: light;') } if (this.settings.language) { - i18n.changeLanguage(this.settings.language); - document.documentElement.setAttribute('lang', this.settings.language === 'dev' ? 'en' : this.settings.language); + i18n.changeLanguage(this.settings.language) + document.documentElement.setAttribute( + 'lang', + this.settings.language === 'dev' ? 'en' : this.settings.language + ) } - if (saveConfig) - saveConfigs(); - }; + if (saveConfig) saveConfigs() + } setIntroduction = (value: IntroductionContent) => { - this.introduction = value; - }; + this.introduction = value + } setAbout = (value: AboutContent) => { - this.about = value; - }; + this.about = value + } setLastModelName(value: string) { - this.lastModelName = value; + this.lastModelName = value } setDepComplete = (value: boolean, inSaveCache: boolean = true) => { - this.depComplete = value; - if (inSaveCache) - saveCache(); - }; + this.depComplete = value + if (inSaveCache) saveCache() + } setDownloadList = (value: DownloadStatus[]) => { - this.downloadList = value; - }; + this.downloadList = value + } setConversation = (value: Conversation) => { - this.conversation = value; - }; + this.conversation = value + } setConversationOrder = (value: string[]) => { - this.conversationOrder = value; - }; + this.conversationOrder = value + } setCompletionPreset(value: CompletionPreset) { - this.completionPreset = value; + this.completionPreset = value } setCompletionGenerating(value: boolean) { - this.completionGenerating = value; + this.completionGenerating = value } setMonitorData(value: MonitorData) { - this.monitorData = value; + this.monitorData = value } setPlatform(value: Platform) { - this.platform = value; + this.platform = value } setProxyPort(value: number) { - this.proxyPort = value; + this.proxyPort = value } setCurrentInput(value: string) { - this.currentInput = value; + this.currentInput = value } setAdvancedCollapsed(value: boolean) { - this.advancedCollapsed = value; + this.advancedCollapsed = value } setApiParamsCollapsed(value: boolean) { - this.apiParamsCollapsed = value; + this.apiParamsCollapsed = value } setModelParamsCollapsed(value: boolean) { - this.modelParamsCollapsed = value; + this.modelParamsCollapsed = value } setLastUnfinishedModelDownloads(value: DownloadStatus[]) { - this.lastUnfinishedModelDownloads = value; + this.lastUnfinishedModelDownloads = value } setEditingPreset(value: Preset | null) { - this.editingPreset = value; + this.editingPreset = value } setPresets(value: Preset[], savePreset: boolean = true) { - this.presets = value; - if (savePreset) - savePresets(); + this.presets = value + if (savePreset) savePresets() } setActivePreset(value: Preset | null) { - this.activePreset = value; + this.activePreset = value } setActivePresetIndex(value: number) { - this.activePresetIndex = value; + this.activePresetIndex = value } setCompletionSubmittedPrompt(value: string) { - this.completionSubmittedPrompt = value; + this.completionSubmittedPrompt = value } setCompositionParams(value: CompositionParams) { - this.compositionParams = value; + this.compositionParams = value } setCompositionGenerating(value: boolean) { - this.compositionGenerating = value; + this.compositionGenerating = value } setCompositionSubmittedPrompt(value: string) { - this.compositionSubmittedPrompt = value; + this.compositionSubmittedPrompt = value } setWslStdout(value: string) { - this.wslStdout = value; + this.wslStdout = value } - setDataProcessParams(value: DataProcessParameters, saveConfig: boolean = true) { - this.dataProcessParams = value; - if (saveConfig) - saveConfigs(); + setDataProcessParams( + value: DataProcessParameters, + saveConfig: boolean = true + ) { + this.dataProcessParams = value + if (saveConfig) saveConfigs() } - setLoraFinetuneParameters(value: LoraFinetuneParameters, saveConfig: boolean = true) { - this.loraFinetuneParams = value; - if (saveConfig) - saveConfigs(); + setLoraFinetuneParameters( + value: LoraFinetuneParameters, + saveConfig: boolean = true + ) { + this.loraFinetuneParams = value + if (saveConfig) saveConfigs() } setChartTitle(value: string) { - this.chartTitle = value; + this.chartTitle = value } setChartData(value: ChartData<'line', (number | null)[], string>) { - this.chartData = value; + this.chartData = value } setLoraModels(value: string[]) { - this.loraModels = value; + this.loraModels = value } setStateModels(value: string[]) { - this.stateModels = value; + this.stateModels = value } setAttachmentUploading(value: boolean) { - this.attachmentUploading = value; + this.attachmentUploading = value } - setAttachments(value: { - [uuid: string]: Attachment[] - }) { - this.attachments = value; + setAttachments(value: { [uuid: string]: Attachment[] }) { + this.attachments = value } setAttachment(uuid: string, value: Attachment[] | null) { - if (value === null) - delete this.attachments[uuid]; - else - this.attachments[uuid] = value; + if (value === null) delete this.attachments[uuid] + else this.attachments[uuid] = value } setCurrentTempAttachment(value: Attachment | null) { - this.currentTempAttachment = value; + this.currentTempAttachment = value } setChatParams(value: Partial) { - this.chatParams = { ...this.chatParams, ...value }; + this.chatParams = { ...this.chatParams, ...value } } setSidePanelCollapsed(value: boolean | 'auto') { - this.sidePanelCollapsed = value; + this.sidePanelCollapsed = value } setTracks(value: Track[]) { - this.tracks = value; + this.tracks = value } setTrackScale(value: number) { - this.trackScale = value; + this.trackScale = value } setTrackTotalTime(value: number) { - this.trackTotalTime = value; + this.trackTotalTime = value } setTrackCurrentTime(value: number) { - this.trackCurrentTime = value; + this.trackCurrentTime = value } setTrackPlayStartTime(value: number) { - this.trackPlayStartTime = value; + this.trackPlayStartTime = value } setMidiPorts(value: MidiPort[]) { - this.midiPorts = value; + this.midiPorts = value } setInstrumentType(value: InstrumentType) { - this.instrumentType = value; + this.instrumentType = value } setRecordingTrackId(value: string) { - this.recordingTrackId = value; + this.recordingTrackId = value } setActiveMidiDeviceIndex(value: number) { - this.activeMidiDeviceIndex = value; + this.activeMidiDeviceIndex = value } setRecordingContent(value: string) { - this.recordingContent = value; + this.recordingContent = value } setRecordingRawContent(value: MidiMessage[]) { - this.recordingRawContent = value; + this.recordingRawContent = value } setPlayingTrackId(value: string) { - this.playingTrackId = value; + this.playingTrackId = value } setActiveModelListTags(value: string[]) { - this.activeModelListTags = value; + this.activeModelListTags = value } } -export default new CommonStore(); \ No newline at end of file +export default new CommonStore() diff --git a/frontend/src/style.scss b/frontend/src/style.scss index 3be21326..6aba13d1 100644 --- a/frontend/src/style.scss +++ b/frontend/src/style.scss @@ -74,12 +74,13 @@ midi-player { } midi-visualizer { - $instrument-colors: #007bff, #20c997, #dc3545, #6610f2, #ffc107, #e83e8c, #17a2b8, #fd7e14, #28a745; + $instrument-colors: #007bff, #20c997, #dc3545, #6610f2, #ffc107, #e83e8c, + #17a2b8, #fd7e14, #28a745; svg { @for $i from 0 to 200 { $color: nth($instrument-colors, ($i % length($instrument-colors)) + 1); - rect.note[data-instrument="#{$i}"] { + rect.note[data-instrument='#{$i}'] { fill: $color; } } diff --git a/frontend/src/types/about.ts b/frontend/src/types/about.ts index fc646996..78043f62 100644 --- a/frontend/src/types/about.ts +++ b/frontend/src/types/about.ts @@ -1 +1 @@ -export type AboutContent = { [lang: string]: string } \ No newline at end of file +export type AboutContent = { [lang: string]: string } diff --git a/frontend/src/types/chat.ts b/frontend/src/types/chat.ts index c93eec76..ccf1b72b 100644 --- a/frontend/src/types/chat.ts +++ b/frontend/src/types/chat.ts @@ -1,41 +1,54 @@ -import { ApiParameters } from './configs'; +import { ApiParameters } from './configs' -export const userName = 'M E'; -export const botName = 'A I'; -export const systemName = 'System'; -export const welcomeUuid = 'welcome'; +export const userName = 'M E' +export const botName = 'A I' +export const systemName = 'System' +export const welcomeUuid = 'welcome' export enum MessageType { Normal, - Error + Error, } export type Side = 'left' | 'right' | 'center' export type Color = 'neutral' | 'brand' | 'colorful' export type MessageItem = { - sender: string, - type: MessageType, - color: Color, - avatarImg?: string, - time: string, - content: string, - side: Side, + sender: string + toolName?: string + type: MessageType + color: Color + avatarImg?: string + time: string + content: string + side: Side done: boolean } export type Conversation = { [uuid: string]: MessageItem } -export type Role = 'assistant' | 'user' | 'system'; +export type Role = 'assistant' | 'user' | 'system' | 'tool' export type ConversationMessage = { - role: Role; - content: string; + role: Role + content: string + tool_call_id?: string + tool_calls?: Array<{ + id: string + type: 'function' + function: { + name: string + arguments: string + } + }> } export type Attachment = { - name: string; - size: number; - content: string; + name: string + size: number + content: string } export type ChatParams = Omit & { - historyN: number; - markdown: boolean; -} \ No newline at end of file + historyN: number + markdown: boolean + functionCall: boolean + toolDefinition: string + toolReturn: string +} diff --git a/frontend/src/types/completion.ts b/frontend/src/types/completion.ts index 993c941b..861a1d5d 100644 --- a/frontend/src/types/completion.ts +++ b/frontend/src/types/completion.ts @@ -1,12 +1,12 @@ -import { ApiParameters } from './configs'; +import { ApiParameters } from './configs' export type CompletionParams = Omit & { - stop: string, - injectStart: string, + stop: string + injectStart: string injectEnd: string -}; +} export type CompletionPreset = { - name: string, - prompt: string, + name: string + prompt: string params: CompletionParams -} \ No newline at end of file +} diff --git a/frontend/src/types/composition.ts b/frontend/src/types/composition.ts index f574881a..61843290 100644 --- a/frontend/src/types/composition.ts +++ b/frontend/src/types/composition.ts @@ -1,42 +1,42 @@ -import { NoteSequence } from '@magenta/music/esm/protobuf'; +import { NoteSequence } from '@magenta/music/esm/protobuf' -export const tracksMinimalTotalTime = 5000; +export const tracksMinimalTotalTime = 5000 export type CompositionParams = { - prompt: string, - maxResponseToken: number, - temperature: number, - topP: number, - autoPlay: boolean, - useLocalSoundFont: boolean, - externalPlay: boolean, - midi: ArrayBuffer | null, - ns: NoteSequence | null, - generationStartTime: number, - playOnlyGeneratedContent: boolean, + prompt: string + maxResponseToken: number + temperature: number + topP: number + autoPlay: boolean + useLocalSoundFont: boolean + externalPlay: boolean + midi: ArrayBuffer | null + ns: NoteSequence | null + generationStartTime: number + playOnlyGeneratedContent: boolean } export type Track = { - id: string; - mainInstrument: string; - content: string; - rawContent: MidiMessage[]; - offsetTime: number; - contentTime: number; -}; + id: string + mainInstrument: string + content: string + rawContent: MidiMessage[] + offsetTime: number + contentTime: number +} export type MidiPort = { - name: string; + name: string } -export type MessageType = 'NoteOff' | 'NoteOn' | 'ElapsedTime' | 'ControlChange'; +export type MessageType = 'NoteOff' | 'NoteOn' | 'ElapsedTime' | 'ControlChange' export type MidiMessage = { - messageType: MessageType; - channel: number; - note: number; - velocity: number; - control: number; - value: number; - instrument: InstrumentType; + messageType: MessageType + channel: number + note: number + velocity: number + control: number + value: number + instrument: InstrumentType } export enum InstrumentType { @@ -68,8 +68,8 @@ export const InstrumentTypeNameMap = [ 'Sax', 'Flute', 'Lead', - 'Pad' -]; + 'Pad', +] export const InstrumentTypeTokenMap = [ 'pi', @@ -84,5 +84,5 @@ export const InstrumentTypeTokenMap = [ 's', 'f', 'l', - 'pa' -]; + 'pa', +] diff --git a/frontend/src/types/configs.ts b/frontend/src/types/configs.ts index a8668ef7..4b30f5d0 100644 --- a/frontend/src/types/configs.ts +++ b/frontend/src/types/configs.ts @@ -1,34 +1,42 @@ export type ApiParameters = { apiPort: number - maxResponseToken: number; - temperature: number; - topP: number; - presencePenalty: number; - frequencyPenalty: number; - penaltyDecay?: number; - globalPenalty?: boolean; - stateModel?: string; + maxResponseToken: number + temperature: number + topP: number + presencePenalty: number + frequencyPenalty: number + penaltyDecay?: number + globalPenalty?: boolean + stateModel?: string } -export type Device = 'CPU' | 'CPU (rwkv.cpp)' | 'CUDA' | 'CUDA-Beta' | 'WebGPU' | 'WebGPU (Python)' | 'MPS' | 'Custom'; -export type Precision = 'fp16' | 'int8' | 'fp32' | 'nf4' | 'Q5_1'; +export type Device = + | 'CPU' + | 'CPU (rwkv.cpp)' + | 'CUDA' + | 'CUDA-Beta' + | 'WebGPU' + | 'WebGPU (Python)' + | 'MPS' + | 'Custom' +export type Precision = 'fp16' | 'int8' | 'fp32' | 'nf4' | 'Q5_1' export type ModelParameters = { // different models can not have the same name - modelName: string; - device: Device; - precision: Precision; - storedLayers: number; - maxStoredLayers: number; - quantizedLayers?: number; - tokenChunkSize?: number; - useCustomCuda?: boolean; - customStrategy?: string; - useCustomTokenizer?: boolean; - customTokenizer?: string; + modelName: string + device: Device + precision: Precision + storedLayers: number + maxStoredLayers: number + quantizedLayers?: number + tokenChunkSize?: number + useCustomCuda?: boolean + customStrategy?: string + useCustomTokenizer?: boolean + customTokenizer?: string } export type ModelConfig = { // different configs can have the same name - name: string; - apiParameters: ApiParameters; - modelParameters: ModelParameters; - enableWebUI?: boolean; -} \ No newline at end of file + name: string + apiParameters: ApiParameters + modelParameters: ModelParameters + enableWebUI?: boolean +} diff --git a/frontend/src/types/downloads.ts b/frontend/src/types/downloads.ts index 5718ec24..2deeb213 100644 --- a/frontend/src/types/downloads.ts +++ b/frontend/src/types/downloads.ts @@ -1,11 +1,11 @@ export type DownloadStatus = { - name: string; - path: string; - url: string; - transferred: number; - size: number; - speed: number; - progress: number; - downloading: boolean; - done: boolean; -} \ No newline at end of file + name: string + path: string + url: string + transferred: number + size: number + speed: number + progress: number + downloading: boolean + done: boolean +} diff --git a/frontend/src/types/home.ts b/frontend/src/types/home.ts index 29555280..ff6096f7 100644 --- a/frontend/src/types/home.ts +++ b/frontend/src/types/home.ts @@ -1,11 +1,11 @@ -import { ReactElement } from 'react'; +import { ReactElement } from 'react' export type IntroductionContent = { [lang: string]: string } export type NavCard = { - label: string; - desc: string; - path: string; - icon: ReactElement; -}; \ No newline at end of file + label: string + desc: string + path: string + icon: ReactElement +} diff --git a/frontend/src/types/html-midi-player.d.ts b/frontend/src/types/html-midi-player.d.ts index 05471b73..a38a6525 100644 --- a/frontend/src/types/html-midi-player.d.ts +++ b/frontend/src/types/html-midi-player.d.ts @@ -1,9 +1,9 @@ declare module JSX { - import { PlayerElement } from 'html-midi-player'; - import { VisualizerElement } from 'html-midi-player'; + import { PlayerElement } from 'html-midi-player' + import { VisualizerElement } from 'html-midi-player' interface IntrinsicElements { - 'midi-player': PlayerElement; - 'midi-visualizer': VisualizerElement; + 'midi-player': PlayerElement + 'midi-visualizer': VisualizerElement } -} \ No newline at end of file +} diff --git a/frontend/src/types/models.ts b/frontend/src/types/models.ts index 78b86eab..956af930 100644 --- a/frontend/src/types/models.ts +++ b/frontend/src/types/models.ts @@ -1,17 +1,18 @@ export type ModelSourceItem = { - name: string; - desc?: { [lang: string]: string | undefined; }; - size: number; - SHA256?: string; - lastUpdated: string; - url?: string; - downloadUrl?: string; - tags?: string[]; - customTokenizer?: string; - hide?: boolean; + name: string + desc?: { [lang: string]: string | undefined } + size: number + SHA256?: string + lastUpdated: string + url?: string + downloadUrl?: string + tags?: string[] + customTokenizer?: string + hide?: boolean + functionCall?: boolean - lastUpdatedMs?: number; - isComplete?: boolean; - isLocal?: boolean; - localSize?: number; -}; \ No newline at end of file + lastUpdatedMs?: number + isComplete?: boolean + isLocal?: boolean + localSize?: number +} diff --git a/frontend/src/types/presets.ts b/frontend/src/types/presets.ts index 5680bed6..bd85bf1e 100644 --- a/frontend/src/types/presets.ts +++ b/frontend/src/types/presets.ts @@ -1,31 +1,30 @@ -import { ReactElement } from 'react'; - -import { ConversationMessage } from './chat'; +import { ReactElement } from 'react' +import { ConversationMessage } from './chat' export type PresetType = 'chat' | 'completion' | 'chatInCompletion' export type Preset = { - name: string, - tag: string, + name: string + tag: string // if name and sourceUrl are same, it will be overridden when importing - sourceUrl: string, - desc: string, - avatarImg: string, - userAvatarImg?: string, - type: PresetType, + sourceUrl: string + desc: string + avatarImg: string + userAvatarImg?: string + type: PresetType // chat - welcomeMessage: string, - messages: ConversationMessage[], - displayPresetMessages: boolean, + welcomeMessage: string + messages: ConversationMessage[] + displayPresetMessages: boolean // completion - prompt: string, - stop: string, - injectStart: string, - injectEnd: string, - presystem?: boolean, - userName?: string, + prompt: string + stop: string + injectStart: string + injectEnd: string + presystem?: boolean + userName?: string assistantName?: string } export type PresetsNavigationItem = { - icon: ReactElement; - element: ReactElement; -}; \ No newline at end of file + icon: ReactElement + element: ReactElement +} diff --git a/frontend/src/types/settings.ts b/frontend/src/types/settings.ts index 127e2442..299f83be 100644 --- a/frontend/src/types/settings.ts +++ b/frontend/src/types/settings.ts @@ -1,9 +1,9 @@ export const Languages = { dev: 'English', // i18n default zh: '简体中文', - ja: '日本語' -}; -export type Language = keyof typeof Languages; + ja: '日本語', +} +export type Language = keyof typeof Languages export type SettingsType = { language: Language darkMode: boolean @@ -20,4 +20,4 @@ export type SettingsType = { apiChatModelName: string apiCompletionModelName: string coreApiUrl: string -} \ No newline at end of file +} diff --git a/frontend/src/types/train.ts b/frontend/src/types/train.ts index fd056f81..a260c165 100644 --- a/frontend/src/types/train.ts +++ b/frontend/src/types/train.ts @@ -1,35 +1,35 @@ -import { ReactElement } from 'react'; +import { ReactElement } from 'react' export type DataProcessParameters = { - dataPath: string; - vocabPath: string; + dataPath: string + vocabPath: string } -export type LoraFinetunePrecision = 'bf16' | 'fp16' | 'tf32'; +export type LoraFinetunePrecision = 'bf16' | 'fp16' | 'tf32' export type LoraFinetuneParameters = { - baseModel: string; - ctxLen: number; - epochSteps: number; - epochCount: number; - epochBegin: number; - epochSave: number; - microBsz: number; - accumGradBatches: number; - preFfn: boolean; - headQk: boolean; - lrInit: string; - lrFinal: string; - warmupSteps: number; - beta1: number; - beta2: number; - adamEps: string; - devices: number; - precision: LoraFinetunePrecision; - gradCp: boolean; - loraR: number; - loraAlpha: number; - loraDropout: number; + baseModel: string + ctxLen: number + epochSteps: number + epochCount: number + epochBegin: number + epochSave: number + microBsz: number + accumGradBatches: number + preFfn: boolean + headQk: boolean + lrInit: string + lrFinal: string + warmupSteps: number + beta1: number + beta2: number + adamEps: string + devices: number + precision: LoraFinetunePrecision + gradCp: boolean + loraR: number + loraAlpha: number + loraDropout: number loraLoad: string } export type TrainNavigationItem = { - element: ReactElement; -}; \ No newline at end of file + element: ReactElement +} diff --git a/frontend/src/utils/convert-model.ts b/frontend/src/utils/convert-model.ts index 1705b6e8..77c1d5ba 100644 --- a/frontend/src/utils/convert-model.ts +++ b/frontend/src/utils/convert-model.ts @@ -1,118 +1,183 @@ -import { toast } from 'react-toastify'; -import commonStore from '../stores/commonStore'; -import { t } from 'i18next'; +import { t } from 'i18next' +import { NavigateFunction } from 'react-router' +import { toast } from 'react-toastify' import { ConvertGGML, ConvertModel, ConvertSafetensors, ConvertSafetensorsWithPython, FileExists, - GetPyError -} from '../../wailsjs/go/backend_golang/App'; -import { WindowShow } from '../../wailsjs/runtime'; -import { ModelConfig, Precision } from '../types/configs'; -import { checkDependencies, getStrategy } from './index'; -import { NavigateFunction } from 'react-router'; + GetPyError, +} from '../../wailsjs/go/backend_golang/App' +import { WindowShow } from '../../wailsjs/runtime' +import commonStore from '../stores/commonStore' +import { ModelConfig, Precision } from '../types/configs' +import { checkDependencies, getStrategy } from './index' -export const convertModel = async (selectedConfig: ModelConfig, navigate: NavigateFunction) => { +export const convertModel = async ( + selectedConfig: ModelConfig, + navigate: NavigateFunction +) => { if (commonStore.platform === 'darwin') { - toast(t('MacOS is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_model.py)', { type: 'info' }); - return; + toast( + t( + 'MacOS is not yet supported for performing this operation, please do it manually.' + ) + ' (backend-python/convert_model.py)', + { type: 'info' } + ) + return } else if (commonStore.platform === 'linux') { - toast(t('Linux is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_model.py)', { type: 'info' }); - return; + toast( + t( + 'Linux is not yet supported for performing this operation, please do it manually.' + ) + ' (backend-python/convert_model.py)', + { type: 'info' } + ) + return } - const ok = await checkDependencies(navigate); - if (!ok) - return; + const ok = await checkDependencies(navigate) + if (!ok) return - const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}`; + const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}` if (await FileExists(modelPath)) { - const strategy = getStrategy(selectedConfig); - const newModelPath = modelPath + '-' + strategy.replace(/[:> *+]/g, '-'); - toast(t('Start Converting'), { autoClose: 2000, type: 'info' }); - ConvertModel(commonStore.settings.customPythonPath, modelPath, strategy, newModelPath).then(async () => { - if (!await FileExists(newModelPath + '.pth')) { - toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' }); - } else { - toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' }); - } - }).catch(e => { - const errMsg = e.message || e; - if (errMsg.includes('path contains space')) - toast(`${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' }); - else - toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' }); - }); - setTimeout(WindowShow, 1000); + const strategy = getStrategy(selectedConfig) + const newModelPath = modelPath + '-' + strategy.replace(/[:> *+]/g, '-') + toast(t('Start Converting'), { autoClose: 2000, type: 'info' }) + ConvertModel( + commonStore.settings.customPythonPath, + modelPath, + strategy, + newModelPath + ) + .then(async () => { + if (!(await FileExists(newModelPath + '.pth'))) { + toast(t('Convert Failed') + ' - ' + (await GetPyError()), { + type: 'error', + }) + } else { + toast(`${t('Convert Success')} - ${newModelPath}`, { + type: 'success', + }) + } + }) + .catch((e) => { + const errMsg = e.message || e + if (errMsg.includes('path contains space')) + toast( + `${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, + { type: 'error' } + ) + else + toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' }) + }) + setTimeout(WindowShow, 1000) } else { - toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' }); + toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' }) } -}; +} - -export const convertToSt = async (selectedConfig: ModelConfig, navigate: NavigateFunction) => { - const webgpuPython = selectedConfig.modelParameters.device === 'WebGPU (Python)'; +export const convertToSt = async ( + selectedConfig: ModelConfig, + navigate: NavigateFunction +) => { + const webgpuPython = + selectedConfig.modelParameters.device === 'WebGPU (Python)' if (webgpuPython) { - const ok = await checkDependencies(navigate); - if (!ok) - return; + const ok = await checkDependencies(navigate) + if (!ok) return } - const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}`; + const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}` if (await FileExists(modelPath)) { - toast(t('Start Converting'), { autoClose: 2000, type: 'info' }); - const newModelPath = modelPath.replace(/\.pth$/, '.st'); - const convert = webgpuPython ? - (input: string, output: string) => ConvertSafetensorsWithPython(commonStore.settings.customPythonPath, input, output) - : ConvertSafetensors; - convert(modelPath, newModelPath).then(async () => { - if (!await FileExists(newModelPath)) { - if (commonStore.platform === 'windows' || commonStore.platform === 'linux') - toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' }); - } else { - toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' }); - } - }).catch(e => { - const errMsg = e.message || e; - if (errMsg.includes('path contains space')) - toast(`${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' }); - else - toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' }); - }); - setTimeout(WindowShow, 1000); + toast(t('Start Converting'), { autoClose: 2000, type: 'info' }) + const newModelPath = modelPath.replace(/\.pth$/, '.st') + const convert = webgpuPython + ? (input: string, output: string) => + ConvertSafetensorsWithPython( + commonStore.settings.customPythonPath, + input, + output + ) + : ConvertSafetensors + convert(modelPath, newModelPath) + .then(async () => { + if (!(await FileExists(newModelPath))) { + if ( + commonStore.platform === 'windows' || + commonStore.platform === 'linux' + ) + toast(t('Convert Failed') + ' - ' + (await GetPyError()), { + type: 'error', + }) + } else { + toast(`${t('Convert Success')} - ${newModelPath}`, { + type: 'success', + }) + } + }) + .catch((e) => { + const errMsg = e.message || e + if (errMsg.includes('path contains space')) + toast( + `${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, + { type: 'error' } + ) + else + toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' }) + }) + setTimeout(WindowShow, 1000) } else { - toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' }); + toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' }) } -}; +} -export const convertToGGML = async (selectedConfig: ModelConfig, navigate: NavigateFunction) => { - const ok = await checkDependencies(navigate); - if (!ok) - return; +export const convertToGGML = async ( + selectedConfig: ModelConfig, + navigate: NavigateFunction +) => { + const ok = await checkDependencies(navigate) + if (!ok) return - const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}`; + const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}` if (await FileExists(modelPath)) { - toast(t('Start Converting'), { autoClose: 2000, type: 'info' }); - const precision: Precision = selectedConfig.modelParameters.precision === 'Q5_1' ? 'Q5_1' : 'fp16'; - const newModelPath = modelPath.replace(/\.pth$/, `-${precision}.bin`); - ConvertGGML(commonStore.settings.customPythonPath, modelPath, newModelPath, precision === 'Q5_1').then(async () => { - if (!await FileExists(newModelPath)) { - if (commonStore.platform === 'windows' || commonStore.platform === 'linux') - toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' }); - } else { - toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' }); - } - }).catch(e => { - const errMsg = e.message || e; - if (errMsg.includes('path contains space')) - toast(`${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' }); - else - toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' }); - }); - setTimeout(WindowShow, 1000); + toast(t('Start Converting'), { autoClose: 2000, type: 'info' }) + const precision: Precision = + selectedConfig.modelParameters.precision === 'Q5_1' ? 'Q5_1' : 'fp16' + const newModelPath = modelPath.replace(/\.pth$/, `-${precision}.bin`) + ConvertGGML( + commonStore.settings.customPythonPath, + modelPath, + newModelPath, + precision === 'Q5_1' + ) + .then(async () => { + if (!(await FileExists(newModelPath))) { + if ( + commonStore.platform === 'windows' || + commonStore.platform === 'linux' + ) + toast(t('Convert Failed') + ' - ' + (await GetPyError()), { + type: 'error', + }) + } else { + toast(`${t('Convert Success')} - ${newModelPath}`, { + type: 'success', + }) + } + }) + .catch((e) => { + const errMsg = e.message || e + if (errMsg.includes('path contains space')) + toast( + `${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, + { type: 'error' } + ) + else + toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' }) + }) + setTimeout(WindowShow, 1000) } else { - toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' }); + toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' }) } -}; \ No newline at end of file +} diff --git a/frontend/src/utils/index.tsx b/frontend/src/utils/index.tsx index e4069141..4e48ee68 100644 --- a/frontend/src/utils/index.tsx +++ b/frontend/src/utils/index.tsx @@ -1,3 +1,11 @@ +import { Button } from '@fluentui/react-components' +import { t } from 'i18next' +import { findLastIndex, throttle } from 'lodash-es' +import { NavigateFunction } from 'react-router' +import { toast } from 'react-toastify' +import { ToastOptions } from 'react-toastify/dist/types' +import { v4 as uuid } from 'uuid' +import manifest from '../../../manifest.json' import { AddToDownloadList, DeleteFile, @@ -9,27 +17,35 @@ import { ReadFileInfo, ReadJson, SaveJson, - UpdateApp -} from '../../wailsjs/go/backend_golang/App'; -import manifest from '../../../manifest.json'; -import commonStore, { ModelStatus } from '../stores/commonStore'; -import { toast } from 'react-toastify'; -import { t } from 'i18next'; -import { ToastOptions } from 'react-toastify/dist/types'; -import { Button } from '@fluentui/react-components'; -import { BrowserOpenURL, EventsOff, EventsOn, WindowShow } from '../../wailsjs/runtime'; -import { NavigateFunction } from 'react-router'; -import { ModelConfig, ModelParameters } from '../types/configs'; -import { DownloadStatus } from '../types/downloads'; -import { ModelSourceItem } from '../types/models'; -import { Language, Languages, SettingsType } from '../types/settings'; -import { DataProcessParameters, LoraFinetuneParameters } from '../types/train'; -import { InstrumentTypeNameMap, MidiMessage, tracksMinimalTotalTime } from '../types/composition'; -import logo from '../assets/images/logo.png'; -import { Preset } from '../types/presets'; -import { botName, Conversation, MessageType, Role, systemName, userName } from '../types/chat'; -import { v4 as uuid } from 'uuid'; -import { findLastIndex, throttle } from 'lodash-es'; + UpdateApp, +} from '../../wailsjs/go/backend_golang/App' +import { + BrowserOpenURL, + EventsOff, + EventsOn, + WindowShow, +} from '../../wailsjs/runtime' +import logo from '../assets/images/logo.png' +import commonStore, { ModelStatus } from '../stores/commonStore' +import { + botName, + Conversation, + MessageType, + Role, + systemName, + userName, +} from '../types/chat' +import { + InstrumentTypeNameMap, + MidiMessage, + tracksMinimalTotalTime, +} from '../types/composition' +import { ModelConfig, ModelParameters } from '../types/configs' +import { DownloadStatus } from '../types/downloads' +import { ModelSourceItem } from '../types/models' +import { Preset } from '../types/presets' +import { Language, Languages, SettingsType } from '../types/settings' +import { DataProcessParameters, LoraFinetuneParameters } from '../types/train' export type Cache = { version: string @@ -41,646 +57,860 @@ export type LocalConfig = { modelSourceManifestList: string currentModelConfigIndex: number modelConfigs: ModelConfig[] - settings: SettingsType, - dataProcessParams: DataProcessParameters, + settings: SettingsType + dataProcessParams: DataProcessParameters loraFinetuneParams: LoraFinetuneParameters } export async function refreshBuiltInModels(readCache: boolean = false) { let cache: { models: ModelSourceItem[] - } = { models: [] }; + } = { models: [] } if (readCache) - await ReadJson('cache.json').then((cacheData: Cache) => { - if (cacheData.models) - cache.models = cacheData.models; - else cache.models = manifest.models.slice(); - }).catch(() => { - cache.models = manifest.models.slice(); - }); - else cache.models = manifest.models.slice(); - - commonStore.setModelSourceList(cache.models); - saveCache(); - return cache; + await ReadJson('cache.json') + .then((cacheData: Cache) => { + if (cacheData.models) cache.models = cacheData.models + else cache.models = manifest.models.slice() + }) + .catch(() => { + cache.models = manifest.models.slice() + }) + else cache.models = manifest.models.slice() + + commonStore.setModelSourceList(cache.models) + saveCache() + return cache } -const modelSuffix = ['.pth', '.st', '.safetensors', '.bin']; +const modelSuffix = ['.pth', '.st', '.safetensors', '.bin'] -export async function refreshLocalModels(cache: { - models: ModelSourceItem[] -}, filter: boolean = true, initUnfinishedModels: boolean = false) { - if (filter) - cache.models = cache.models.filter(m => !m.isComplete); //TODO BUG cause local but in manifest files to be removed, so currently cache is disabled - - await ListDirFiles(commonStore.settings.customModelsPath).then((data) => { - cache.models.push(...data.flatMap(d => { - if (!d.isDir && modelSuffix.some((ext => d.name.endsWith(ext)))) - return [{ - name: d.name, - size: d.size, - lastUpdated: d.modTime, - isComplete: true, - isLocal: true, - tags: ['Local'] - }] as ModelSourceItem[]; - return []; - })); - }).catch(() => { - }); +export async function refreshLocalModels( + cache: { + models: ModelSourceItem[] + }, + filter: boolean = true, + initUnfinishedModels: boolean = false +) { + if (filter) cache.models = cache.models.filter((m) => !m.isComplete) //TODO BUG cause local but in manifest files to be removed, so currently cache is disabled + + await ListDirFiles(commonStore.settings.customModelsPath) + .then((data) => { + cache.models.push( + ...data.flatMap((d) => { + if (!d.isDir && modelSuffix.some((ext) => d.name.endsWith(ext))) + return [ + { + name: d.name, + size: d.size, + lastUpdated: d.modTime, + isComplete: true, + isLocal: true, + tags: ['Local'], + }, + ] as ModelSourceItem[] + return [] + }) + ) + }) + .catch(() => {}) for (let i = 0; i < cache.models.length; i++) { if (!cache.models[i].lastUpdatedMs) - cache.models[i].lastUpdatedMs = Date.parse(cache.models[i].lastUpdated); - if (!cache.models[i].tags || !Array.isArray(cache.models[i].tags) || cache.models[i].tags?.length === 0) - cache.models[i].tags = ['Other']; + cache.models[i].lastUpdatedMs = Date.parse(cache.models[i].lastUpdated) + if ( + !cache.models[i].tags || + !Array.isArray(cache.models[i].tags) || + cache.models[i].tags?.length === 0 + ) + cache.models[i].tags = ['Other'] for (let j = i + 1; j < cache.models.length; j++) { if (!cache.models[j].lastUpdatedMs) - cache.models[j].lastUpdatedMs = Date.parse(cache.models[j].lastUpdated); + cache.models[j].lastUpdatedMs = Date.parse(cache.models[j].lastUpdated) if (cache.models[i].name === cache.models[j].name) { - const tags = Array.from(new Set([...cache.models[i].tags as string[], ...cache.models[j].tags as string[]])); - if (cache.models[i].size <= cache.models[j].size) { // j is local file + const tags = Array.from( + new Set([ + ...(cache.models[i].tags as string[]), + ...(cache.models[j].tags as string[]), + ]) + ) + if (cache.models[i].size <= cache.models[j].size) { + // j is local file if (cache.models[i].lastUpdatedMs! < cache.models[j].lastUpdatedMs!) { - cache.models[i] = Object.assign({}, cache.models[i], cache.models[j]); + cache.models[i] = Object.assign( + {}, + cache.models[i], + cache.models[j] + ) } else { - cache.models[i] = Object.assign({}, cache.models[j], cache.models[i]); + cache.models[i] = Object.assign( + {}, + cache.models[j], + cache.models[i] + ) } } // else is not complete local file - cache.models[i].isLocal = true; - cache.models[i].localSize = cache.models[j].size; - cache.models[i].tags = tags; - cache.models.splice(j, 1); - j--; + cache.models[i].isLocal = true + cache.models[i].localSize = cache.models[j].size + cache.models[i].tags = tags + cache.models.splice(j, 1) + j-- } } } - commonStore.setModelSourceList(cache.models); - if (initUnfinishedModels) - initLastUnfinishedModelDownloads(); - saveCache(); + commonStore.setModelSourceList(cache.models) + if (initUnfinishedModels) initLastUnfinishedModelDownloads() + saveCache() } function initLastUnfinishedModelDownloads() { - const list: DownloadStatus[] = []; + const list: DownloadStatus[] = [] commonStore.modelSourceList.forEach((item) => { if (item.isLocal && !item.isComplete) { - list.push( - { - name: item.name, - path: `${commonStore.settings.customModelsPath}/${item.name}`, - url: getHfDownloadUrl(item.downloadUrl!), - transferred: item.localSize!, - size: item.size, - speed: 0, - progress: item.localSize! / item.size * 100, - downloading: false, - done: false - } - ); + list.push({ + name: item.name, + path: `${commonStore.settings.customModelsPath}/${item.name}`, + url: getHfDownloadUrl(item.downloadUrl!), + transferred: item.localSize!, + size: item.size, + speed: 0, + progress: (item.localSize! / item.size) * 100, + downloading: false, + done: false, + }) } - }); - commonStore.setLastUnfinishedModelDownloads(list); + }) + commonStore.setLastUnfinishedModelDownloads(list) } -export async function refreshRemoteModels(cache: { - models: ModelSourceItem[] -}, filter: boolean = true, initUnfinishedModels: boolean = false) { - const manifestUrls = commonStore.modelSourceManifestList.split(/[,,;;\n]/); - const requests = manifestUrls.filter(url => url.endsWith('.json')).map( - url => fetch(url, { cache: 'no-cache' }).then(r => r.json())); +export async function refreshRemoteModels( + cache: { + models: ModelSourceItem[] + }, + filter: boolean = true, + initUnfinishedModels: boolean = false +) { + const manifestUrls = commonStore.modelSourceManifestList.split(/[,,;;\n]/) + const requests = manifestUrls + .filter((url) => url.endsWith('.json')) + .map((url) => fetch(url, { cache: 'no-cache' }).then((r) => r.json())) await Promise.allSettled(requests) - .then((data: PromiseSettledResult[]) => { - cache.models.push(...data.flatMap(d => { - if (d.status === 'fulfilled') - return d.value.models; - return []; - })); - }) - .catch(() => { - }); + .then((data: PromiseSettledResult[]) => { + cache.models.push( + ...data.flatMap((d) => { + if (d.status === 'fulfilled') return d.value.models + return [] + }) + ) + }) + .catch(() => {}) cache.models = cache.models.filter((model, index, self) => { - return modelSuffix.some((ext => model.name.endsWith(ext))) - && index === findLastIndex(self, - m => m.name === model.name || (!!m.SHA256 && m.SHA256 === model.SHA256 && m.size === model.size)); - }); - await refreshLocalModels(cache, filter, initUnfinishedModels); -} - -export const refreshModels = async (readCache: boolean = false, initUnfinishedModels: boolean = false) => { - const cache = await refreshBuiltInModels(readCache); - await refreshLocalModels(cache, false, initUnfinishedModels); - await refreshRemoteModels(cache, false, initUnfinishedModels); -}; - -export const getStrategy = (modelConfig: ModelConfig | undefined = undefined) => { - let params: ModelParameters; - if (modelConfig) params = modelConfig.modelParameters; - else params = commonStore.getCurrentModelConfig().modelParameters; - const modelName = params.modelName.toLowerCase(); - const avoidOverflow = params.precision !== 'fp32' && modelName.includes('world') && (modelName.includes('0.1b') || modelName.includes('0.4b') || - modelName.includes('1.5b') || modelName.includes('1b5')); - let strategy = ''; + return ( + modelSuffix.some((ext) => model.name.endsWith(ext)) && + index === + findLastIndex( + self, + (m) => + m.name === model.name || + (!!m.SHA256 && m.SHA256 === model.SHA256 && m.size === model.size) + ) + ) + }) + await refreshLocalModels(cache, filter, initUnfinishedModels) +} + +export const refreshModels = async ( + readCache: boolean = false, + initUnfinishedModels: boolean = false +) => { + const cache = await refreshBuiltInModels(readCache) + await refreshLocalModels(cache, false, initUnfinishedModels) + await refreshRemoteModels(cache, false, initUnfinishedModels) +} + +export const getStrategy = ( + modelConfig: ModelConfig | undefined = undefined +) => { + let params: ModelParameters + if (modelConfig) params = modelConfig.modelParameters + else params = commonStore.getCurrentModelConfig().modelParameters + const modelName = params.modelName.toLowerCase() + const avoidOverflow = + params.precision !== 'fp32' && + modelName.includes('world') && + (modelName.includes('0.1b') || + modelName.includes('0.4b') || + modelName.includes('1.5b') || + modelName.includes('1b5')) + let strategy = '' switch (params.device) { case 'CPU': - if (avoidOverflow) - strategy = 'cpu fp32 *1 -> '; - strategy += 'cpu '; - strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32'; - break; + if (avoidOverflow) strategy = 'cpu fp32 *1 -> ' + strategy += 'cpu ' + strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32' + break case 'WebGPU': case 'WebGPU (Python)': - strategy += params.precision === 'nf4' ? 'fp16i4' : params.precision === 'int8' ? 'fp16i8' : 'fp16'; - if (params.quantizedLayers) - strategy += ` layer${params.quantizedLayers}`; - if (params.tokenChunkSize) - strategy += ` chunk${params.tokenChunkSize}`; - break; + strategy += + params.precision === 'nf4' + ? 'fp16i4' + : params.precision === 'int8' + ? 'fp16i8' + : 'fp16' + if (params.quantizedLayers) strategy += ` layer${params.quantizedLayers}` + if (params.tokenChunkSize) strategy += ` chunk${params.tokenChunkSize}` + break case 'CUDA': case 'CUDA-Beta': if (avoidOverflow) - strategy = params.useCustomCuda ? 'cuda fp16 *1 -> ' : 'cuda fp32 *1 -> '; - strategy += 'cuda '; - strategy += params.precision === 'int8' ? 'fp16i8' : params.precision === 'fp32' ? 'fp32' : 'fp16'; + strategy = params.useCustomCuda + ? 'cuda fp16 *1 -> ' + : 'cuda fp32 *1 -> ' + strategy += 'cuda ' + strategy += + params.precision === 'int8' + ? 'fp16i8' + : params.precision === 'fp32' + ? 'fp32' + : 'fp16' if (params.storedLayers < params.maxStoredLayers) - strategy += ` *${params.storedLayers}+`; - else - strategy += ` -> cuda fp16 *1`; - break; + strategy += ` *${params.storedLayers}+` + else strategy += ` -> cuda fp16 *1` + break case 'MPS': - if (avoidOverflow) - strategy = 'mps fp32 *1 -> '; - strategy += 'mps '; - strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32'; - break; + if (avoidOverflow) strategy = 'mps fp32 *1 -> ' + strategy += 'mps ' + strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32' + break case 'Custom': - strategy = params.customStrategy || ''; - break; + strategy = params.customStrategy || '' + break } - return strategy; -}; + return strategy +} -export const saveConfigs = throttle(async () => { +export const saveConfigs = throttle( + async () => { const data: LocalConfig = { modelSourceManifestList: commonStore.modelSourceManifestList, currentModelConfigIndex: commonStore.currentModelConfigIndex, modelConfigs: commonStore.modelConfigs, settings: commonStore.settings, dataProcessParams: commonStore.dataProcessParams, - loraFinetuneParams: commonStore.loraFinetuneParams - }; - return SaveJson('config.json', data); - }, 500, + loraFinetuneParams: commonStore.loraFinetuneParams, + } + return SaveJson('config.json', data) + }, + 500, { leading: true, - trailing: true - }); + trailing: true, + } +) -export const saveCache = throttle(async () => { +export const saveCache = throttle( + async () => { const data: Cache = { version: manifest.version, models: commonStore.modelSourceList, - depComplete: commonStore.depComplete - }; - return SaveJson('cache.json', data); - }, 1000, + depComplete: commonStore.depComplete, + } + return SaveJson('cache.json', data) + }, + 1000, { leading: true, - trailing: true - }); + trailing: true, + } +) export const savePresets = async () => { - return SaveJson('presets.json', commonStore.presets); -}; + return SaveJson('presets.json', commonStore.presets) +} export function getUserLanguage(): Language { // const l = navigator.language.toLowerCase(); // if (['zh-hk', 'zh-mo', 'zh-tw', 'zh-cht', 'zh-hant'].includes(l)) return 'zhHant' - const l = navigator.language.substring(0, 2); - if (l in Languages) return l as Language; - return 'dev'; + const l = navigator.language.substring(0, 2) + if (l in Languages) return l as Language + return 'dev' } export function isSystemLightMode() { - return window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches; + return ( + window.matchMedia && + window.matchMedia('(prefers-color-scheme: light)').matches + ) } export function downloadProgramFiles() { manifest.programFiles.forEach(({ url, path }) => { if (path) - ReadFileInfo(path).then(info => { - if (info.size === 0 && url) - AddToDownloadList(path, url.replace('@master', '@v' + manifest.version)); - }).catch(() => { - if (url) - AddToDownloadList(path, url.replace('@master', '@v' + manifest.version)); - }); - }); + ReadFileInfo(path) + .then((info) => { + if (info.size === 0 && url) + AddToDownloadList( + path, + url.replace('@master', '@v' + manifest.version) + ) + }) + .catch(() => { + if (url) + AddToDownloadList( + path, + url.replace('@master', '@v' + manifest.version) + ) + }) + }) } export function forceDownloadProgramFiles() { manifest.programFiles.forEach(({ url, path }) => { if (path && url) - AddToDownloadList(path, url.replace('@master', '@v' + manifest.version)); - }); + AddToDownloadList(path, url.replace('@master', '@v' + manifest.version)) + }) } export async function deleteDynamicProgramFiles() { - let promises: Promise[] = []; + let promises: Promise[] = [] manifest.programFiles.forEach(({ path }) => { - if ((path.endsWith('.py') && !path.includes('get-pip.py')) || path.includes('requirements') || path.endsWith('.pyd')) - promises.push(DeleteFile(path)); - }); - return await Promise.allSettled(promises).catch(() => { - }); + if ( + (path.endsWith('.py') && !path.includes('get-pip.py')) || + path.includes('requirements') || + path.endsWith('.pyd') + ) + promises.push(DeleteFile(path)) + }) + return await Promise.allSettled(promises).catch(() => {}) } export function bytesToGb(size: number) { - return (size / 1024 / 1024 / 1024).toFixed(2); + return (size / 1024 / 1024 / 1024).toFixed(2) } export function bytesToMb(size: number) { - return (size / 1024 / 1024).toFixed(2); + return (size / 1024 / 1024).toFixed(2) } export function bytesToKb(size: number) { - return (size / 1024).toFixed(2); + return (size / 1024).toFixed(2) } export function bytesToReadable(size: number) { - if (size < 1024) return size + ' B'; - else if (size < 1024 * 1024) return bytesToKb(size) + ' KB'; - else if (size < 1024 * 1024 * 1024) return bytesToMb(size) + ' MB'; - else return bytesToGb(size) + ' GB'; + if (size < 1024) return size + ' B' + else if (size < 1024 * 1024) return bytesToKb(size) + ' KB' + else if (size < 1024 * 1024 * 1024) return bytesToMb(size) + ' MB' + else return bytesToGb(size) + ' GB' } -export async function getReqUrl(port: number, path: string, isCore: boolean = false): Promise<{ - url: string, +export async function getReqUrl( + port: number, + path: string, + isCore: boolean = false +): Promise<{ + url: string headers: { [key: string]: string } }> { - const realUrl = getServerRoot(port, isCore) + path; + const realUrl = getServerRoot(port, isCore) + path if (commonStore.platform === 'web' || realUrl.startsWith('https')) return { url: realUrl, - headers: {} - }; + headers: {}, + } if (!commonStore.proxyPort) - await GetProxyPort().then(p => commonStore.setProxyPort(p)); + await GetProxyPort().then((p) => commonStore.setProxyPort(p)) return { url: `http://127.0.0.1:${commonStore.proxyPort}`, - headers: { 'Real-Target': encodeURIComponent(realUrl) } - }; + headers: { 'Real-Target': encodeURIComponent(realUrl) }, + } } -export function getServerRoot(defaultLocalPort: number, isCore: boolean = false) { - const coreCustomApiUrl = commonStore.settings.coreApiUrl.trim().replace(/\/$/, ''); - if (isCore && coreCustomApiUrl) - return coreCustomApiUrl; - - const defaultRoot = `http://127.0.0.1:${defaultLocalPort}`; - if (commonStore.status.status !== ModelStatus.Offline) - return defaultRoot; - const customApiUrl = commonStore.settings.apiUrl.trim().replace(/\/$/, ''); - if (customApiUrl) - return customApiUrl; - if (commonStore.platform === 'web') - return ''; - return defaultRoot; +export function getServerRoot( + defaultLocalPort: number, + isCore: boolean = false +) { + const coreCustomApiUrl = commonStore.settings.coreApiUrl + .trim() + .replace(/\/$/, '') + if (isCore && coreCustomApiUrl) return coreCustomApiUrl + + const defaultRoot = `http://127.0.0.1:${defaultLocalPort}` + if (commonStore.status.status !== ModelStatus.Offline) return defaultRoot + const customApiUrl = commonStore.settings.apiUrl.trim().replace(/\/$/, '') + if (customApiUrl) return customApiUrl + if (commonStore.platform === 'web') return '' + return defaultRoot } export function absPathAsset(path: string) { - if (commonStore.platform === 'web') - return path; - if (path === logo) - return path; - if ((path.length > 0 && path[0] === '/') || - (path.length > 1 && path[1] === ':')) { - return '=>' + path; + if (commonStore.platform === 'web') return path + if (path === logo) return path + if ( + (path.length > 0 && path[0] === '/') || + (path.length > 1 && path[1] === ':') + ) { + return '=>' + path } - return path; + return path } export async function checkUpdate(notifyEvenLatest: boolean = false) { - fetch(!commonStore.settings.giteeUpdatesSource ? - 'https://api.github.com/repos/josstorer/RWKV-Runner/releases/latest' : - 'https://gitee.com/api/v5/repos/josc146/RWKV-Runner/releases/latest' - ).then((r) => { + fetch( + !commonStore.settings.giteeUpdatesSource + ? 'https://api.github.com/repos/josstorer/RWKV-Runner/releases/latest' + : 'https://gitee.com/api/v5/repos/josc146/RWKV-Runner/releases/latest' + ) + .then((r) => { if (r.ok) { r.json().then((data) => { if (data.tag_name) { - const versionTag = data.tag_name; + const versionTag = data.tag_name if (versionTag.replace('v', '') > manifest.version) { - const verifyUrl = !commonStore.settings.giteeUpdatesSource ? - `https://api.github.com/repos/josstorer/RWKV-Runner/releases/tags/${versionTag}` : - `https://gitee.com/api/v5/repos/josc146/RWKV-Runner/releases/tags/${versionTag}`; + const verifyUrl = !commonStore.settings.giteeUpdatesSource + ? `https://api.github.com/repos/josstorer/RWKV-Runner/releases/tags/${versionTag}` + : `https://gitee.com/api/v5/repos/josc146/RWKV-Runner/releases/tags/${versionTag}` fetch(verifyUrl).then((r) => { if (r.ok) { r.json().then((data) => { if (data.assets && data.assets.length > 0) { - const asset = data.assets.find((a: any) => a.name.toLowerCase().includes(commonStore.platform.toLowerCase().replace('darwin', 'macos'))); + const asset = data.assets.find((a: any) => + a.name + .toLowerCase() + .includes( + commonStore.platform + .toLowerCase() + .replace('darwin', 'macos') + ) + ) if (asset) { - const updateUrl = !commonStore.settings.giteeUpdatesSource ? - `https://github.com/josStorer/RWKV-Runner/releases/download/${versionTag}/${asset.name}` : - `https://gitee.com/josc146/RWKV-Runner/releases/download/${versionTag}/${asset.name}`; - toastWithButton(t('New Version Available') + ': ' + versionTag, t('Update'), () => { - DeleteFile('cache.json'); - const progressId = 'update_app'; - const progressEvent = 'updateApp'; - const updateProgress = (ds: DownloadStatus | null) => { - const content = - t('Downloading update, please wait. If it is not completed, please manually download the program from GitHub and replace the original program.') - + (ds ? ` (${ds.progress.toFixed(2)}% ${bytesToReadable(ds.transferred)}/${bytesToReadable(ds.size)})` : ''); - const options: ToastOptions = { - type: 'info', - position: 'bottom-left', - autoClose: false, - toastId: progressId, - hideProgressBar: false, - progress: ds ? ds.progress / 100 : 0 - }; - if (toast.isActive(progressId)) - toast.update(progressId, { - render: content, - ...options - }); - else - toast(content, options); - }; - updateProgress(null); - EventsOn(progressEvent, updateProgress); - UpdateApp(updateUrl).then(() => { - toast(t('Update completed, please restart the program.'), { - type: 'success', + const updateUrl = !commonStore.settings + .giteeUpdatesSource + ? `https://github.com/josStorer/RWKV-Runner/releases/download/${versionTag}/${asset.name}` + : `https://gitee.com/josc146/RWKV-Runner/releases/download/${versionTag}/${asset.name}` + toastWithButton( + t('New Version Available') + ': ' + versionTag, + t('Update'), + () => { + DeleteFile('cache.json') + const progressId = 'update_app' + const progressEvent = 'updateApp' + const updateProgress = ( + ds: DownloadStatus | null + ) => { + const content = + t( + 'Downloading update, please wait. If it is not completed, please manually download the program from GitHub and replace the original program.' + ) + + (ds + ? ` (${ds.progress.toFixed(2)}% ${bytesToReadable(ds.transferred)}/${bytesToReadable(ds.size)})` + : '') + const options: ToastOptions = { + type: 'info', position: 'bottom-left', - autoClose: false + autoClose: false, + toastId: progressId, + hideProgressBar: false, + progress: ds ? ds.progress / 100 : 0, } - ); - }).catch((e) => { - toast(t('Update Error') + ' - ' + (e.message || e), { - type: 'error', - position: 'bottom-left', - autoClose: false - }); - }).finally(() => { - toast.dismiss(progressId); - EventsOff(progressEvent); - }); - }, { - autoClose: false, - position: 'bottom-left' - }); + if (toast.isActive(progressId)) + toast.update(progressId, { + render: content, + ...options, + }) + else toast(content, options) + } + updateProgress(null) + EventsOn(progressEvent, updateProgress) + UpdateApp(updateUrl) + .then(() => { + toast( + t( + 'Update completed, please restart the program.' + ), + { + type: 'success', + position: 'bottom-left', + autoClose: false, + } + ) + }) + .catch((e) => { + toast( + t('Update Error') + ' - ' + (e.message || e), + { + type: 'error', + position: 'bottom-left', + autoClose: false, + } + ) + }) + .finally(() => { + toast.dismiss(progressId) + EventsOff(progressEvent) + }) + }, + { + autoClose: false, + position: 'bottom-left', + } + ) } } - }); + }) } else { - throw new Error('Verify response was not ok.'); + throw new Error('Verify response was not ok.') } - }); + }) } else { if (notifyEvenLatest) { - toast(t('This is the latest version'), { type: 'success', position: 'bottom-left', autoClose: 2000 }); + toast(t('This is the latest version'), { + type: 'success', + position: 'bottom-left', + autoClose: 2000, + }) } } } else { - throw new Error('Invalid response.'); + throw new Error('Invalid response.') } - }); + }) } else { - throw new Error('Network response was not ok.'); + throw new Error('Network response was not ok.') } - } - ).catch((e) => { - toast(t('Updates Check Error') + ' - ' + (e.message || e), { type: 'error', position: 'bottom-left' }); - }); + }) + .catch((e) => { + toast(t('Updates Check Error') + ' - ' + (e.message || e), { + type: 'error', + position: 'bottom-left', + }) + }) } export const checkDependencies = async (navigate: NavigateFunction) => { if (!commonStore.depComplete) { - let depErrorMsg = ''; + let depErrorMsg = '' await DepCheck(commonStore.settings.customPythonPath).catch((e) => { - depErrorMsg = e.message || e; - WindowShow(); + depErrorMsg = e.message || e + WindowShow() if (depErrorMsg === 'python zip not found') { - toastWithButton(t('Python target not found, would you like to download it?'), t('Download'), () => { - toastWithButton(`${t('Downloading')} Python`, t('Check'), () => { - navigate({ pathname: '/downloads' }); - }, { autoClose: 3000 }); - AddToDownloadList('python-3.10.11-embed-amd64.zip', - !commonStore.settings.cnMirror - ? 'https://www.python.org/ftp/python/3.10.11/python-3.10.11-embed-amd64.zip' - : 'https://mirrors.huaweicloud.com/python/3.10.11/python-3.10.11-embed-amd64.zip'); - }); + toastWithButton( + t('Python target not found, would you like to download it?'), + t('Download'), + () => { + toastWithButton( + `${t('Downloading')} Python`, + t('Check'), + () => { + navigate({ pathname: '/downloads' }) + }, + { autoClose: 3000 } + ) + AddToDownloadList( + 'python-3.10.11-embed-amd64.zip', + !commonStore.settings.cnMirror + ? 'https://www.python.org/ftp/python/3.10.11/python-3.10.11-embed-amd64.zip' + : 'https://mirrors.huaweicloud.com/python/3.10.11/python-3.10.11-embed-amd64.zip' + ) + } + ) } else if (depErrorMsg.includes('DepCheck Error')) { - if (depErrorMsg.includes('vc_redist') || depErrorMsg.includes('DLL load failed while importing')) { - toastWithButton(t('Microsoft Visual C++ Redistributable is not installed, would you like to download it?'), t('Download'), () => { - BrowserOpenURL('https://aka.ms/vs/16/release/vc_redist.x64.exe'); - }); + if ( + depErrorMsg.includes('vc_redist') || + depErrorMsg.includes('DLL load failed while importing') + ) { + toastWithButton( + t( + 'Microsoft Visual C++ Redistributable is not installed, would you like to download it?' + ), + t('Download'), + () => { + BrowserOpenURL('https://aka.ms/vs/16/release/vc_redist.x64.exe') + } + ) } else { - toast(depErrorMsg, { type: 'info', position: 'bottom-left' }); + toast(depErrorMsg, { type: 'info', position: 'bottom-left' }) if (commonStore.platform !== 'linux') - toastWithButton(t('Python dependencies are incomplete, would you like to install them?'), t('Install'), () => { - InstallPyDep(commonStore.settings.customPythonPath, commonStore.settings.cnMirror).catch((e) => { - const errMsg = e.message || e; - toast(t('Error') + ' - ' + errMsg, { type: 'error' }); - }); - setTimeout(WindowShow, 1000); - }, { - autoClose: 8000 - }); + toastWithButton( + t( + 'Python dependencies are incomplete, would you like to install them?' + ), + t('Install'), + () => { + InstallPyDep( + commonStore.settings.customPythonPath, + commonStore.settings.cnMirror + ).catch((e) => { + const errMsg = e.message || e + toast(t('Error') + ' - ' + errMsg, { type: 'error' }) + }) + setTimeout(WindowShow, 1000) + }, + { + autoClose: 8000, + } + ) else - toastWithButton(t('On Linux system, you must manually install python dependencies.'), t('Check'), () => { - BrowserOpenURL('https://github.com/josStorer/RWKV-Runner/blob/master/build/linux/Readme_Install.txt'); - }); + toastWithButton( + t( + 'On Linux system, you must manually install python dependencies.' + ), + t('Check'), + () => { + BrowserOpenURL( + 'https://github.com/josStorer/RWKV-Runner/blob/master/build/linux/Readme_Install.txt' + ) + } + ) } } else { - toast(depErrorMsg, { type: 'error' }); + toast(depErrorMsg, { type: 'error' }) } - }); + }) if (depErrorMsg) { - commonStore.setStatus({ status: ModelStatus.Offline }); - return false; + commonStore.setStatus({ status: ModelStatus.Offline }) + return false } - commonStore.setDepComplete(true); + commonStore.setDepComplete(true) } - return true; -}; + return true +} -export function toastWithButton(text: string, buttonText: string, onClickButton: () => void, options?: ToastOptions) { - let triggered = false; +export function toastWithButton( + text: string, + buttonText: string, + onClickButton: () => void, + options?: ToastOptions +) { + let triggered = false const id = toast(
{text}
- +
, { type: 'info', - ...options - }); - return id; + ...options, + } + ) + return id } export function getHfDownloadUrl(url: string) { - if (commonStore.settings.useHfMirror && url.includes('huggingface.co') && url.includes('resolve')) - return url.replace('huggingface.co', 'hf-mirror.com'); - return url; + if ( + commonStore.settings.useHfMirror && + url.includes('huggingface.co') && + url.includes('resolve') + ) + return url.replace('huggingface.co', 'hf-mirror.com') + return url } export function refreshTracksTotalTime() { if (commonStore.tracks.length === 0) { - commonStore.setTrackTotalTime(tracksMinimalTotalTime); - commonStore.setTrackCurrentTime(0); - commonStore.setTrackPlayStartTime(0); - return; + commonStore.setTrackTotalTime(tracksMinimalTotalTime) + commonStore.setTrackCurrentTime(0) + commonStore.setTrackPlayStartTime(0) + return } - const endTimes = commonStore.tracks.map(t => t.offsetTime + t.contentTime); - const totalTime = Math.max(...endTimes) + tracksMinimalTotalTime; + const endTimes = commonStore.tracks.map((t) => t.offsetTime + t.contentTime) + const totalTime = Math.max(...endTimes) + tracksMinimalTotalTime if (commonStore.trackPlayStartTime > totalTime) - commonStore.setTrackPlayStartTime(totalTime); - commonStore.setTrackTotalTime(totalTime); + commonStore.setTrackPlayStartTime(totalTime) + commonStore.setTrackTotalTime(totalTime) } export function getMidiRawContentTime(rawContent: MidiMessage[]) { - return rawContent.reduce((sum, current) => - sum + (current.messageType === 'ElapsedTime' ? current.value : 0) - , 0); + return rawContent.reduce( + (sum, current) => + sum + (current.messageType === 'ElapsedTime' ? current.value : 0), + 0 + ) } export function getMidiRawContentMainInstrument(rawContent: MidiMessage[]) { - const sortedInstrumentFrequency = Object.entries(rawContent - .filter(c => c.messageType === 'NoteOn') - .map(c => c.instrument) - .reduce((frequencyCount, current) => (frequencyCount[current] = (frequencyCount[current] || 0) + 1, frequencyCount) - , {} as { - [key: string]: number - })) - .sort((a, b) => b[1] - a[1]); - let mainInstrument: string = ''; + const sortedInstrumentFrequency = Object.entries( + rawContent + .filter((c) => c.messageType === 'NoteOn') + .map((c) => c.instrument) + .reduce( + (frequencyCount, current) => ( + (frequencyCount[current] = (frequencyCount[current] || 0) + 1), + frequencyCount + ), + {} as { + [key: string]: number + } + ) + ).sort((a, b) => b[1] - a[1]) + let mainInstrument: string = '' if (sortedInstrumentFrequency.length > 0) - mainInstrument = InstrumentTypeNameMap[Number(sortedInstrumentFrequency[0][0])]; - return mainInstrument; + mainInstrument = + InstrumentTypeNameMap[Number(sortedInstrumentFrequency[0][0])] + return mainInstrument } export function flushMidiRecordingContent() { - const recordingTrackIndex = commonStore.tracks.findIndex(t => t.id === commonStore.recordingTrackId); + const recordingTrackIndex = commonStore.tracks.findIndex( + (t) => t.id === commonStore.recordingTrackId + ) if (recordingTrackIndex >= 0) { - const recordingTrack = commonStore.tracks[recordingTrackIndex]; - const tracks = commonStore.tracks.slice(); + const recordingTrack = commonStore.tracks[recordingTrackIndex] + const tracks = commonStore.tracks.slice() tracks[recordingTrackIndex] = { ...recordingTrack, content: commonStore.recordingContent, rawContent: commonStore.recordingRawContent, contentTime: getMidiRawContentTime(commonStore.recordingRawContent), - mainInstrument: getMidiRawContentMainInstrument(commonStore.recordingRawContent) - }; - commonStore.setTracks(tracks); - refreshTracksTotalTime(); + mainInstrument: getMidiRawContentMainInstrument( + commonStore.recordingRawContent + ), + } + commonStore.setTracks(tracks) + refreshTracksTotalTime() } - commonStore.setRecordingContent(''); - commonStore.setRecordingRawContent([]); + commonStore.setRecordingContent('') + commonStore.setRecordingRawContent([]) } export async function getSoundFont() { - let soundUrl: string; + let soundUrl: string if (commonStore.compositionParams.useLocalSoundFont) - soundUrl = 'assets/sound-font'; + soundUrl = 'assets/sound-font' else - soundUrl = !commonStore.settings.giteeUpdatesSource ? - `https://raw.githubusercontent.com/josStorer/sgm_plus/master` : - `https://cdn.jsdelivr.net/gh/josstorer/sgm_plus`; - const fallbackUrl = 'https://cdn.jsdelivr.net/gh/josstorer/sgm_plus'; - await fetch(soundUrl + '/soundfont.json').then(r => { - if (!r.ok) - soundUrl = fallbackUrl; - }).catch(() => soundUrl = fallbackUrl); - return soundUrl; + soundUrl = !commonStore.settings.giteeUpdatesSource + ? `https://raw.githubusercontent.com/josStorer/sgm_plus/master` + : `https://cdn.jsdelivr.net/gh/josstorer/sgm_plus` + const fallbackUrl = 'https://cdn.jsdelivr.net/gh/josstorer/sgm_plus' + await fetch(soundUrl + '/soundfont.json') + .then((r) => { + if (!r.ok) soundUrl = fallbackUrl + }) + .catch(() => (soundUrl = fallbackUrl)) + return soundUrl } export const setActivePreset = (preset: Preset | null, index: number) => { - commonStore.setActivePreset(preset); - commonStore.setActivePresetIndex(index); + commonStore.setActivePreset(preset) + commonStore.setActivePresetIndex(index) //TODO if (preset.displayPresetMessages) { - const { pushMessage, saveConversation } = newChatConversation(); + const { pushMessage, saveConversation } = newChatConversation() if (preset) for (const message of preset.messages) { - pushMessage(message.role, message.content); + pushMessage(message.role, message.content) } - saveConversation(); + saveConversation() //} -}; +} export function getSupportedCustomCudaFile(isBeta: boolean) { - if ([' 10', ' 16', ' 20', ' 30', 'MX', 'Tesla P', 'Quadro P', 'NVIDIA P', 'TITAN X', 'TITAN RTX', 'RTX A', - 'Quadro RTX 4000', 'Quadro RTX 5000', 'Tesla T4', 'NVIDIA A10', 'NVIDIA A40'].some(v => commonStore.status.device_name.includes(v))) - return isBeta ? - './backend-python/wkv_cuda_utils/beta/wkv_cuda10_30.pyd' : - './backend-python/wkv_cuda_utils/wkv_cuda10_30.pyd'; - else if ([' 40', 'RTX 5000 Ada', 'RTX 6000 Ada', 'RTX TITAN Ada', 'NVIDIA L40'].some(v => commonStore.status.device_name.includes(v))) - return isBeta ? - './backend-python/wkv_cuda_utils/beta/wkv_cuda40.pyd' : - './backend-python/wkv_cuda_utils/wkv_cuda40.pyd'; - else - return ''; + if ( + [ + ' 10', + ' 16', + ' 20', + ' 30', + 'MX', + 'Tesla P', + 'Quadro P', + 'NVIDIA P', + 'TITAN X', + 'TITAN RTX', + 'RTX A', + 'Quadro RTX 4000', + 'Quadro RTX 5000', + 'Tesla T4', + 'NVIDIA A10', + 'NVIDIA A40', + ].some((v) => commonStore.status.device_name.includes(v)) + ) + return isBeta + ? './backend-python/wkv_cuda_utils/beta/wkv_cuda10_30.pyd' + : './backend-python/wkv_cuda_utils/wkv_cuda10_30.pyd' + else if ( + [' 40', 'RTX 5000 Ada', 'RTX 6000 Ada', 'RTX TITAN Ada', 'NVIDIA L40'].some( + (v) => commonStore.status.device_name.includes(v) + ) + ) + return isBeta + ? './backend-python/wkv_cuda_utils/beta/wkv_cuda40.pyd' + : './backend-python/wkv_cuda_utils/wkv_cuda40.pyd' + else return '' } // a wrapper for webOpenOpenFileDialog and OpenOpenFileDialog export function OpenFileDialog(filterPattern: string): Promise { return new Promise((resolve) => { - OpenOpenFileDialog(filterPattern).then(async filePath => { - if (!filePath) - return; + OpenOpenFileDialog(filterPattern) + .then(async (filePath) => { + if (!filePath) return - let blob: Blob; + let blob: Blob if (commonStore.platform === 'web') - blob = (filePath as unknown as { blob: Blob }).blob; - else - blob = await fetch(absPathAsset(filePath)).then(r => r.blob()); - - resolve(blob); - }).catch(e => { - toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 }); - }); - } - ); + blob = (filePath as unknown as { blob: Blob }).blob + else blob = await fetch(absPathAsset(filePath)).then((r) => r.blob()) + + resolve(blob) + }) + .catch((e) => { + toast(t('Error') + ' - ' + (e.message || e), { + type: 'error', + autoClose: 2500, + }) + }) + }) } export function newChatConversation() { - const conversation: Conversation = {}; - const conversationOrder: string[] = []; + const conversation: Conversation = {} + const conversationOrder: string[] = [] const pushMessage = (role: Role, content: string) => { - const newUuid = uuid(); - conversationOrder.push(newUuid); + const newUuid = uuid() + conversationOrder.push(newUuid) conversation[newUuid] = { - sender: role === 'user' ? userName : role === 'assistant' ? botName : systemName, + sender: + role === 'user' + ? userName + : role === 'assistant' + ? botName + : systemName, type: MessageType.Normal, color: role === 'user' ? 'brand' : 'neutral', avatarImg: role === 'user' ? undefined : logo, time: new Date().toISOString(), content: content, - side: role === 'user' ? 'right' : role === 'assistant' ? 'left' : 'center', - done: true - }; - }; + side: + role === 'user' ? 'right' : role === 'assistant' ? 'left' : 'center', + done: true, + } + } const saveConversation = () => { - commonStore.setConversation(conversation); - commonStore.setConversationOrder(conversationOrder); - }; - return { pushMessage, saveConversation }; + commonStore.setConversation(conversation) + commonStore.setConversationOrder(conversationOrder) + } + return { pushMessage, saveConversation } } export function isDynamicStateSupported(modelConfig: ModelConfig) { - return modelConfig.modelParameters.device === 'CUDA' || + return ( + modelConfig.modelParameters.device === 'CUDA' || modelConfig.modelParameters.device === 'CPU' || modelConfig.modelParameters.device === 'Custom' || - modelConfig.modelParameters.device === 'MPS'; -} \ No newline at end of file + modelConfig.modelParameters.device === 'MPS' + ) +} diff --git a/frontend/src/utils/web-file-operations.ts b/frontend/src/utils/web-file-operations.ts index 532683d9..44e12f78 100644 --- a/frontend/src/utils/web-file-operations.ts +++ b/frontend/src/utils/web-file-operations.ts @@ -1,77 +1,85 @@ -import { getDocument, GlobalWorkerOptions, PDFDocumentProxy } from 'pdfjs-dist'; -import { TextItem } from 'pdfjs-dist/types/src/display/api'; +import { getDocument, GlobalWorkerOptions, PDFDocumentProxy } from 'pdfjs-dist' +import { TextItem } from 'pdfjs-dist/types/src/display/api' -export function webOpenOpenFileDialog(filterPattern: string, fnStartLoading: Function | undefined): Promise<{ - blob: File, +export function webOpenOpenFileDialog( + filterPattern: string, + fnStartLoading: Function | undefined +): Promise<{ + blob: File content?: string }> { return new Promise((resolve, reject) => { - const input = document.createElement('input'); - input.type = 'file'; + const input = document.createElement('input') + input.type = 'file' input.accept = filterPattern - .replaceAll('*.txt', 'text/plain') - .replace('*.midi', 'audio/midi') - .replace('*.mid', 'audio/midi') - .replaceAll('*.', 'application/') - .replaceAll(';', ','); + .replaceAll('*.txt', 'text/plain') + .replace('*.midi', 'audio/midi') + .replace('*.mid', 'audio/midi') + .replaceAll('*.', 'application/') + .replaceAll(';', ',') - input.onchange = async e => { - const file = (e.target as HTMLInputElement).files?.[0]; + input.onchange = async (e) => { + const file = (e.target as HTMLInputElement).files?.[0] if (!file) return if (fnStartLoading && typeof fnStartLoading === 'function') - fnStartLoading(); + fnStartLoading() if (!GlobalWorkerOptions.workerSrc && file.type === 'application/pdf') - // @ts-ignore - GlobalWorkerOptions.workerSrc = await import('pdfjs-dist/build/pdf.worker.min.mjs'); + GlobalWorkerOptions.workerSrc = await import( + // @ts-ignore + 'pdfjs-dist/build/pdf.worker.min.mjs' + ) if (file.type === 'text/plain') { - const reader = new FileReader(); - reader.readAsText(file, 'UTF-8'); + const reader = new FileReader() + reader.readAsText(file, 'UTF-8') - reader.onload = event => { - const content = event.target?.result as string; + reader.onload = (event) => { + const content = event.target?.result as string resolve({ blob: file, - content: content - }); - }; - reader.onerror = reject; + content: content, + }) + } + reader.onerror = reject } else if (file.type === 'application/pdf') { const readPDFPage = async (doc: PDFDocumentProxy, pageNo: number) => { - const page = await doc.getPage(pageNo); - const tokenizedText = await page.getTextContent(); - return tokenizedText.items.map(token => (token as TextItem).str).join(''); - }; - let reader = new FileReader(); - reader.readAsArrayBuffer(file); + const page = await doc.getPage(pageNo) + const tokenizedText = await page.getTextContent() + return tokenizedText.items + .map((token) => (token as TextItem).str) + .join('') + } + let reader = new FileReader() + reader.readAsArrayBuffer(file) reader.onload = async (event) => { try { - const doc = await getDocument(event.target?.result!).promise; - const pageTextPromises = []; + const doc = await getDocument(event.target?.result!).promise + const pageTextPromises = [] for (let pageNo = 1; pageNo <= doc.numPages; pageNo++) { - pageTextPromises.push(readPDFPage(doc, pageNo)); + pageTextPromises.push(readPDFPage(doc, pageNo)) } - const pageTexts = await Promise.all(pageTextPromises); - let content; - if (pageTexts.length === 1) - content = pageTexts[0]; + const pageTexts = await Promise.all(pageTextPromises) + let content + if (pageTexts.length === 1) content = pageTexts[0] else - content = pageTexts.map((p, i) => `Page ${i + 1}:\n${p}`).join('\n\n'); + content = pageTexts + .map((p, i) => `Page ${i + 1}:\n${p}`) + .join('\n\n') resolve({ blob: file, - content: content - }); + content: content, + }) } catch (err) { - reject(err); + reject(err) } - }; - reader.onerror = reject; + } + reader.onerror = reject } else { resolve({ - blob: file - }); + blob: file, + }) } - }; - input.click(); - }); -} \ No newline at end of file + } + input.click() + }) +} diff --git a/frontend/src/webWails.js b/frontend/src/webWails.js index c96d37d2..5d235453 100644 --- a/frontend/src/webWails.js +++ b/frontend/src/webWails.js @@ -13,16 +13,11 @@ if (!window.runtime) { document.title += ' WebUI' // not implemented - defineRuntime('EventsOnMultiple', () => { - }) - defineRuntime('WindowSetLightTheme', () => { - }) - defineRuntime('WindowSetDarkTheme', () => { - }) - defineRuntime('WindowShow', () => { - }) - defineRuntime('WindowHide', () => { - }) + defineRuntime('EventsOnMultiple', () => {}) + defineRuntime('WindowSetLightTheme', () => {}) + defineRuntime('WindowSetDarkTheme', () => {}) + defineRuntime('WindowShow', () => {}) + defineRuntime('WindowHide', () => {}) // implemented defineRuntime('ClipboardGetText', async () => { @@ -46,64 +41,35 @@ if (!window.go) { window.go['backend_golang']['App'] = {} // not implemented - defineApp('AddToDownloadList', async () => { - }) - defineApp('CloseMidiPort', async () => { - }) - defineApp('ContinueDownload', async () => { - }) - defineApp('ConvertData', async () => { - }) - defineApp('ConvertModel', async () => { - }) - defineApp('ConvertSafetensors', async () => { - }) - defineApp('CopyFile', async () => { - }) - defineApp('DeleteFile', async () => { - }) - defineApp('DepCheck', async () => { - }) - defineApp('DownloadFile', async () => { - }) - defineApp('GetPyError', async () => { - }) - defineApp('InstallPyDep', async () => { - }) - defineApp('IsPortAvailable', async () => { - }) - defineApp('MergeLora', async () => { - }) - defineApp('OpenFileFolder', async () => { - }) - defineApp('OpenMidiPort', async () => { - }) - defineApp('PauseDownload', async () => { - }) - defineApp('PlayNote', async () => { - }) - defineApp('ReadFileInfo', async () => { - }) - defineApp('RestartApp', async () => { - }) - defineApp('StartServer', async () => { - }) - defineApp('StartWebGPUServer', async () => { - }) - defineApp('UpdateApp', async () => { - }) - defineApp('WslCommand', async () => { - }) - defineApp('WslEnable', async () => { - }) - defineApp('WslInstallUbuntu', async () => { - }) - defineApp('WslIsEnabled', async () => { - }) - defineApp('WslStart', async () => { - }) - defineApp('WslStop', async () => { - }) + defineApp('AddToDownloadList', async () => {}) + defineApp('CloseMidiPort', async () => {}) + defineApp('ContinueDownload', async () => {}) + defineApp('ConvertData', async () => {}) + defineApp('ConvertModel', async () => {}) + defineApp('ConvertSafetensors', async () => {}) + defineApp('CopyFile', async () => {}) + defineApp('DeleteFile', async () => {}) + defineApp('DepCheck', async () => {}) + defineApp('DownloadFile', async () => {}) + defineApp('GetPyError', async () => {}) + defineApp('InstallPyDep', async () => {}) + defineApp('IsPortAvailable', async () => {}) + defineApp('MergeLora', async () => {}) + defineApp('OpenFileFolder', async () => {}) + defineApp('OpenMidiPort', async () => {}) + defineApp('PauseDownload', async () => {}) + defineApp('PlayNote', async () => {}) + defineApp('ReadFileInfo', async () => {}) + defineApp('RestartApp', async () => {}) + defineApp('StartServer', async () => {}) + defineApp('StartWebGPUServer', async () => {}) + defineApp('UpdateApp', async () => {}) + defineApp('WslCommand', async () => {}) + defineApp('WslEnable', async () => {}) + defineApp('WslInstallUbuntu', async () => {}) + defineApp('WslIsEnabled', async () => {}) + defineApp('WslStart', async () => {}) + defineApp('WslStop', async () => {}) // implemented defineApp('FileExists', async () => { @@ -122,24 +88,34 @@ if (!window.go) { return 0 }) defineApp('OpenOpenFileDialog', webOpenOpenFileDialog) - defineApp('OpenSaveFileDialog', async (filterPattern, defaultFileName, savedContent) => { - const saver = await import('file-saver') - saver.saveAs(new Blob([savedContent], { type: 'text/plain;charset=utf-8' }), defaultFileName) - return '' - }) - defineApp('OpenSaveFileDialogBytes', async (filterPattern, defaultFileName, savedContent) => { - const saver = await import('file-saver') - saver.saveAs(new Blob([new Uint8Array(savedContent)], { type: 'octet/stream' }), defaultFileName) - return '' - }) + defineApp( + 'OpenSaveFileDialog', + async (filterPattern, defaultFileName, savedContent) => { + const saver = await import('file-saver') + saver.saveAs( + new Blob([savedContent], { type: 'text/plain;charset=utf-8' }), + defaultFileName + ) + return '' + } + ) + defineApp( + 'OpenSaveFileDialogBytes', + async (filterPattern, defaultFileName, savedContent) => { + const saver = await import('file-saver') + saver.saveAs( + new Blob([new Uint8Array(savedContent)], { type: 'octet/stream' }), + defaultFileName + ) + return '' + } + ) defineApp('ReadJson', async (fileName) => { const data = JSON.parse(localStorage.getItem(fileName)) - if (data) - return data - else - throw new Error('File not found') + if (data) return data + else throw new Error('File not found') }) defineApp('SaveJson', async (fileName, data) => { localStorage.setItem(fileName, JSON.stringify(data)) }) -} \ No newline at end of file +} diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js index f955ad58..e9ce6b43 100644 --- a/frontend/tailwind.config.js +++ b/frontend/tailwind.config.js @@ -56,42 +56,29 @@ const markdownElements = [ 's', 'a', 'pre', - 'cite' + 'cite', ] -const markdownPseudoElements = [ - '::marker', - '::before', - '::after' -] +const markdownPseudoElements = ['::marker', '::before', '::after'] -const tableElements = [ - 'table', - 'tr', - 'td', - 'th', - 'thead', - 'tbody', - 'tfoot' -] +const tableElements = ['table', 'tr', 'td', 'th', 'thead', 'tbody', 'tfoot'] const proseStyles = { - color: 'inherit' + color: 'inherit', } const tableProseStyles = { ...proseStyles, borderWidth: 'thin', - borderColor: '#d2d2d5' + borderColor: '#d2d2d5', } const elementsStyles = markdownElements.reduce((acc, element) => { let styles = proseStyles - if (tableElements.includes(element)) - styles = tableProseStyles + if (tableElements.includes(element)) styles = tableProseStyles acc[element] = styles - markdownPseudoElements.forEach(pseudo => { + markdownPseudoElements.forEach((pseudo) => { acc[element + pseudo] = styles }) return acc @@ -99,10 +86,7 @@ const elementsStyles = markdownElements.reduce((acc, element) => { /** @type {import('tailwindcss').Config} */ export default { - content: [ - './index.html', - './src/**/*.{js,ts,jsx,tsx}' - ], + content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'], theme: { extend: { typography: { @@ -110,12 +94,11 @@ export default { css: { color: 'inherit', fontSize: 'inherit', - ...elementsStyles - } - } - } - } + ...elementsStyles, + }, + }, + }, + }, }, - plugins: [require('@tailwindcss/typography')] + plugins: [require('@tailwindcss/typography')], } - diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json index 823e83d1..c7b97298 100644 --- a/frontend/tsconfig.json +++ b/frontend/tsconfig.json @@ -2,11 +2,7 @@ "compilerOptions": { "target": "ESNext", "useDefineForClassFields": true, - "lib": [ - "DOM", - "DOM.Iterable", - "ESNext" - ], + "lib": ["DOM", "DOM.Iterable", "ESNext"], "allowJs": false, "skipLibCheck": true, "esModuleInterop": false, @@ -20,9 +16,7 @@ "noEmit": true, "jsx": "react-jsx" }, - "include": [ - "src" - ], + "include": ["src"], "references": [ { "path": "./tsconfig.node.json" diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json index b8afcc8f..9d31e2ae 100644 --- a/frontend/tsconfig.node.json +++ b/frontend/tsconfig.node.json @@ -5,7 +5,5 @@ "moduleResolution": "Node", "allowSyntheticDefaultImports": true }, - "include": [ - "vite.config.ts" - ] + "include": ["vite.config.ts"] } diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 24b2b541..aafcc1cb 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,19 +1,26 @@ +import react from '@vitejs/plugin-react' +import { visualizer } from 'rollup-plugin-visualizer' +import { defineConfig } from 'vite' +import topLevelAwait from 'vite-plugin-top-level-await' // @ts-ignore -import { dependencies } from './package.json'; -import { defineConfig } from 'vite'; -import react from '@vitejs/plugin-react'; -import { visualizer } from 'rollup-plugin-visualizer'; -import topLevelAwait from 'vite-plugin-top-level-await'; +import { dependencies } from './package.json' // dependencies that exist anywhere const vendor = [ - 'react', 'react-dom', 'react-router', 'react-router-dom', + 'react', + 'react-dom', + 'react-router', + 'react-router-dom', '@fluentui/react-icons', - 'mobx', 'mobx-react-lite', - 'i18next', 'react-i18next', - 'usehooks-ts', 'react-toastify', - 'classnames', 'lodash-es' -]; + 'mobx', + 'mobx-react-lite', + 'i18next', + 'react-i18next', + 'usehooks-ts', + 'react-toastify', + 'classnames', + 'lodash-es', +] const embedded = [ // split @fluentui/react-components by components @@ -22,17 +29,25 @@ const embedded = [ // dependencies that exist in single component 'react-beautiful-dnd', 'react-draggable', - '@magenta/music', 'html-midi-player', - 'react-markdown', 'rehype-highlight', 'rehype-raw', 'remark-breaks', 'remark-gfm', 'remark-math', 'rehype-katex', 'katex' -]; + '@magenta/music', + 'html-midi-player', + 'react-markdown', + 'rehype-highlight', + 'rehype-raw', + 'remark-breaks', + 'remark-gfm', + 'remark-math', + 'rehype-katex', + 'katex', +] function renderChunks(deps: Record) { - let chunks = {}; + let chunks = {} Object.keys(deps).forEach((key) => { - if ([...vendor, ...embedded].includes(key)) return; - chunks[key] = [key]; - }); - return chunks; + if ([...vendor, ...embedded].includes(key)) return + chunks[key] = [key] + }) + return chunks } // https://vitejs.dev/config/ @@ -42,12 +57,12 @@ export default defineConfig({ visualizer({ template: 'treemap', gzipSize: true, - brotliSize: true + brotliSize: true, }), topLevelAwait({ promiseExportName: '__tla', - promiseImportName: i => `__tla_${i}` - }) + promiseImportName: (i) => `__tla_${i}`, + }), ], build: { chunkSizeWarningLimit: 3000, @@ -55,12 +70,12 @@ export default defineConfig({ output: { manualChunks: { vendor, - ...renderChunks(dependencies) + ...renderChunks(dependencies), }, entryFileNames: `assets/[name].js`, chunkFileNames: `assets/[name].js`, - assetFileNames: `assets/[name].[ext]` - } - } - } -}); + assetFileNames: `assets/[name].[ext]`, + }, + }, + }, +}) diff --git a/go.mod b/go.mod index 848ae7f8..c62df0e0 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module rwkv-runner -go 1.22 +go 1.20 require ( github.com/cavaliergopher/grab/v3 v3.0.1 diff --git a/manifest.json b/manifest.json index 6d79fc7c..e7ea9ecd 100644 --- a/manifest.json +++ b/manifest.json @@ -1,5 +1,5 @@ { - "version": "1.8.5", + "version": "1.8.7", "introduction": { "en": "RWKV is an open-source, commercially usable large language model with high flexibility and great potential for development.\n### About This Tool\nThis tool aims to lower the barrier of entry for using large language models, making it accessible to everyone. It provides fully automated dependency and model management. You simply need to click and run, following the instructions, to deploy a local large language model. The tool itself is very compact and only requires a single executable file for one-click deployment.\nAdditionally, this tool offers an interface that is fully compatible with the OpenAI API. This means you can use any ChatGPT client as a client for RWKV, enabling capability expansion beyond just chat functionality.\n### Preset Configuration Rules at the Bottom\nThis tool comes with a series of preset configurations to reduce complexity. The naming rules for each configuration represent the following in order: device - required VRAM/memory - model size - model language.\nFor example, \"GPU-8G-3B-EN\" indicates that this configuration is for a graphics card with 8GB of VRAM, a model size of 3 billion parameters, and it uses an English language model.\nLarger model sizes have higher performance and VRAM requirements. Among configurations with the same model size, those with higher VRAM usage will have faster runtime.\nFor example, if you have 12GB of VRAM but running the \"GPU-12G-7B-EN\" configuration is slow, you can downgrade to \"GPU-8G-3B-EN\" for a significant speed improvement.\n### About RWKV\nRWKV is an RNN with Transformer-level LLM performance, which can also be directly trained like a GPT transformer (parallelizable). And it's 100% attention-free. You only need the hidden state at position t to compute the state at position t+1. You can use the \"GPT\" mode to quickly compute the hidden state for the \"RNN\" mode.
So it's combining the best of RNN and transformer - great performance, fast inference, saves VRAM, fast training, \"infinite\" ctx_len, and free sentence embedding (using the final hidden state).", "zh": "RWKV是一个开源且允许商用的大语言模型,灵活性很高且极具发展潜力。\n### 关于本工具\n本工具旨在降低大语言模型的使用门槛,做到人人可用,本工具提供了全自动化的依赖和模型管理,你只需要直接点击运行,跟随引导,即可完成本地大语言模型的部署,工具本身体积极小,只需要一个exe即可完成一键部署。\n此外,本工具提供了与OpenAI API完全兼容的接口,这意味着你可以把任意ChatGPT客户端用作RWKV的客户端,实现能力拓展,而不局限于聊天。\n### 底部的预设配置规则\n本工具内置了一系列预设配置,以降低使用难度,每个配置名的规则,依次代表着:设备-所需显存/内存-模型规模-模型语言。\n例如,GPU-8G-3B-CN,表示该配置用于显卡,需要8G显存,模型规模为30亿参数,使用的是中文模型。\n模型规模越大,性能要求越高,显存要求也越高,而同样模型规模的配置中,显存占用越高的,运行速度越快。\n例如当你有12G显存,但运行GPU-12G-7B-CN配置速度比较慢,可降级成GPU-8G-3B-CN,将会大幅提速。\n### 关于RWKV\nRWKV是具有Transformer级别LLM性能的RNN,也可以像GPT Transformer一样直接进行训练(可并行化)。而且它是100% attention-free的。你只需在位置t处获得隐藏状态即可计算位置t + 1处的状态。你可以使用“GPT”模式快速计算用于“RNN”模式的隐藏状态。\n因此,它将RNN和Transformer的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。" @@ -141,6 +141,120 @@ "JP" ] }, + { + "name": "RWKV-x060-ChnNovel-1B-20240807-ctx4096.pth", + "desc": { + "en": "RWKV-6 Chinese Novel 1B5", + "zh": "RWKV-6 中文小说 1B5", + "ja": "RWKV-6 中国小説 1B5" + }, + "size": 3199845649, + "SHA256": "98fbd7dfa8cb32dd77457f754a4a97975f68ca3ef73a8312e3e348b29c2d1188", + "lastUpdated": "2024-08-08T05:33:16", + "url": "https://huggingface.co/BlinkDL/rwkv-6-misc/blob/main/RWKV-x060-ChnNovel-1B-20240807-ctx4096.pth", + "downloadUrl": "https://huggingface.co/BlinkDL/rwkv-6-misc/resolve/main/RWKV-x060-ChnNovel-1B-20240807-ctx4096.pth", + "tags": [ + "Official", + "RWKV-6", + "Finetuned", + "CN" + ] + }, + { + "name": "RWKV-x060-ChnNovel-3B-20240807-ctx4096.pth", + "desc": { + "en": "RWKV-6 Chinese Novel 3B", + "zh": "RWKV-6 中文小说 3B", + "ja": "RWKV-6 中国小説 3B" + }, + "size": 6199859229, + "SHA256": "ce8897c573e3a8bc8077153c1bac88984b7a74a488c1966c3676bbe1f2ae16e6", + "lastUpdated": "2024-08-08T05:33:16", + "url": "https://huggingface.co/BlinkDL/rwkv-6-misc/blob/main/RWKV-x060-ChnNovel-3B-20240807-ctx4096.pth", + "downloadUrl": "https://huggingface.co/BlinkDL/rwkv-6-misc/resolve/main/RWKV-x060-ChnNovel-3B-20240807-ctx4096.pth", + "tags": [ + "Official", + "RWKV-6", + "Finetuned", + "CN" + ] + }, + { + "name": "RWKV-x060-ChnNovel-7B-20240803-ctx4096.pth", + "desc": { + "en": "RWKV-6 Chinese Novel 7B", + "zh": "RWKV-6 中文小说 7B", + "ja": "RWKV-6 中国小説 7B" + }, + "size": 15271627101, + "SHA256": "a9a1b0947c887c8fcda3454f3ced4ed7cc099e24c32606effb668a37a22fc83b", + "lastUpdated": "2024-08-03T03:56:57", + "url": "https://huggingface.co/BlinkDL/rwkv-6-misc/blob/main/RWKV-x060-ChnNovel-7B-20240803-ctx4096.pth", + "downloadUrl": "https://huggingface.co/BlinkDL/rwkv-6-misc/resolve/main/RWKV-x060-ChnNovel-7B-20240803-ctx4096.pth", + "tags": [ + "Official", + "RWKV-6", + "Finetuned", + "CN" + ] + }, + { + "name": "RWKV-x060-ChnNovel-14B-20240805-ctx4096.pth", + "desc": { + "en": "RWKV-6 Chinese Novel 14B", + "zh": "RWKV-6 中文小说 14B", + "ja": "RWKV-6 中国小説 14B" + }, + "size": 28138429718, + "SHA256": "10000ec77c65c14992c2ceda49781149f88430fe7b30a2d4f40589e4a7baf490", + "lastUpdated": "2024-08-05T11:37:00", + "url": "https://huggingface.co/BlinkDL/rwkv-6-misc/blob/main/RWKV-x060-ChnNovel-14B-20240805-ctx4096.pth", + "downloadUrl": "https://huggingface.co/BlinkDL/rwkv-6-misc/resolve/main/RWKV-x060-ChnNovel-14B-20240805-ctx4096.pth", + "tags": [ + "Official", + "RWKV-6", + "Finetuned", + "CN" + ] + }, + { + "name": "RWKV-x060-Jpn-7B-20240816-ctx4096.pth", + "desc": { + "en": "RWKV-6 Enhanced Japanese 7B", + "zh": "RWKV-6 日文增强 7B", + "ja": "RWKV-6 日本語強化 7B" + }, + "size": 15271627101, + "SHA256": "7824869dc3b3d15ac9fb40797f6a741e7f6031f8a7a821e3465c0aecddf51fa8", + "lastUpdated": "2024-08-16T15:50:08", + "url": "https://huggingface.co/BlinkDL/rwkv-6-misc/blob/main/RWKV-x060-Jpn-7B-20240816-ctx4096.pth", + "downloadUrl": "https://huggingface.co/BlinkDL/rwkv-6-misc/resolve/main/RWKV-x060-Jpn-7B-20240816-ctx4096.pth", + "tags": [ + "Official", + "RWKV-6", + "Finetuned", + "JP" + ] + }, + { + "name": "RWKV-x060-Jpn-14B-20240819-ctx4096.pth", + "desc": { + "en": "RWKV-6 Enhanced Japanese 14B", + "zh": "RWKV-6 日文增强 14B", + "ja": "RWKV-6 日本語強化 14B" + }, + "size": 28138429782, + "SHA256": "c27c010185b37a6c31cba70e32a5337052221a1ca8e5675e4a6f5dfa73ce490d", + "lastUpdated": "2024-08-19T07:02:22", + "url": "https://huggingface.co/BlinkDL/rwkv-6-misc/blob/main/RWKV-x060-Jpn-14B-20240819-ctx4096.pth", + "downloadUrl": "https://huggingface.co/BlinkDL/rwkv-6-misc/resolve/main/RWKV-x060-Jpn-14B-20240819-ctx4096.pth", + "tags": [ + "Official", + "RWKV-6", + "Finetuned", + "JP" + ] + }, { "name": "RWKV-5-World-0.1B-v1-20230803-ctx4096.pth", "desc": { @@ -175,7 +289,8 @@ "Official", "RWKV-5", "Global" - ] + ], + "hide": true }, { "name": "RWKV-5-World-1B5-v2-20231025-ctx4096.pth", @@ -195,7 +310,8 @@ "Global", "CN", "JP" - ] + ], + "hide": true }, { "name": "RWKV-5-1B5-one-state-slim.pth", @@ -215,7 +331,8 @@ "Global", "Role Play" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "RWKV-5-1B5-one-state-slim-novel-tuned.pth", @@ -234,7 +351,8 @@ "RWKV-5", "Global" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "RWKV-5-World-3B-v2-20231113-ctx4096.pth", @@ -254,7 +372,8 @@ "Global", "CN", "JP" - ] + ], + "hide": true }, { "name": "RWKV-5-World-3B-v2-20231118-ctx16k.pth", @@ -274,7 +393,8 @@ "Global", "CN", "JP" - ] + ], + "hide": true }, { "name": "RWKV-5-World-7B-v2-20240128-ctx4096.pth", @@ -294,7 +414,8 @@ "Global", "CN", "JP" - ] + ], + "hide": true }, { "name": "rwkv-v5-7B-0.4-long-ctx-16k.pth", @@ -313,7 +434,8 @@ "RWKV-5", "Global" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "rwkv-v5.2-7B-horror-16k.pth", @@ -332,7 +454,8 @@ "RWKV-5", "Global" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "rwkv_v5.2_7B_role_play_16k.pth", @@ -352,7 +475,8 @@ "Global", "Role Play" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "RWKV-5-12B-one-state-chat-16k.pth", @@ -371,7 +495,8 @@ "RWKV-5", "Global" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "Mobius-r6-chat-CHNtuned-12b-16k-v5.5.pth", @@ -383,16 +508,18 @@ "size": 23304952860, "SHA256": "25e56f54fff3feddee1c23a098f5556a9afd0f922c8f7e1db3cf22ef6dfdfde4", "lastUpdated": "2024-06-14T15:59:52", - "url": "https://hf-mirror.com/TimeMobius/Mobius-RWKV-r6-12B/blob/main/Mobius-r6-chat-CHNtuned-12b-16k-v5.5.pth", - "downloadUrl": "https://hf-mirror.com/TimeMobius/Mobius-RWKV-r6-12B/resolve/main/Mobius-r6-chat-CHNtuned-12b-16k-v5.5.pth", + "url": "https://huggingface.co/TimeMobius/Mobius-RWKV-r6-12B/blob/main/Mobius-r6-chat-CHNtuned-12b-16k-v5.5.pth", + "downloadUrl": "https://huggingface.co/TimeMobius/Mobius-RWKV-r6-12B/resolve/main/Mobius-r6-chat-CHNtuned-12b-16k-v5.5.pth", "tags": [ "Finetuned", "RWKV-6", "Global", "Recommended", "CN", - "JP" - ] + "JP", + "Function Call" + ], + "functionCall": true }, { "name": "Mobius-r5-chat-12b-128k.pth", @@ -412,7 +539,8 @@ "Global", "CN", "JP" - ] + ], + "hide": true }, { "name": "Mobius-r5-chat-12b-8k-0426.pth", @@ -432,7 +560,8 @@ "Global", "CN", "JP" - ] + ], + "hide": true }, { "name": "RWKV-4-World-CHNtuned-0.1B-v1-20230617-ctx4096.pth", @@ -450,7 +579,8 @@ "Official", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "RWKV-4-World-0.1B-v1-20230520-ctx4096.pth", @@ -468,7 +598,8 @@ "Official", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-World-CHNtuned-0.4B-v1-20230618-ctx4096.pth", @@ -486,7 +617,8 @@ "Official", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "RWKV-4-World-0.4B-v1-20230529-ctx4096.pth", @@ -504,7 +636,8 @@ "Official", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-World-CHNtuned-1.5B-v1-20230620-ctx4096.pth", @@ -522,7 +655,8 @@ "Official", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "RWKV-4-World-1.5B-v1-OnlyForTest_57%_trained-20230529-ctx4096.pth", @@ -584,7 +718,8 @@ "Official", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-for-mobile-4-world-1.5B-20230906-ctx16k.pth", @@ -603,7 +738,8 @@ "RWKV-4", "Global" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "RWKV-4-World-3B-v1-OnlyForTest_35%_trained-20230529-ctx4096.pth", @@ -673,7 +809,8 @@ "Official", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-World-CHNtuned-3B-v1-20230625-ctx4096.pth", @@ -691,7 +828,8 @@ "Official", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "RWKV-4-World-7B-v1-OnlyForTest_30%_trained-20230529-ctx4096.pth", @@ -787,7 +925,8 @@ "Official", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-claude-4-World-7B-20230805-ctx65k.pth", @@ -805,7 +944,8 @@ "Finetuned", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-toolformer-translation-japanese-chinese-english-7B-World-20230815-ctx128k.pth", @@ -823,7 +963,8 @@ "Finetuned", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-code-4-World-7B-20230820-ctx32k.pth", @@ -841,7 +982,8 @@ "Finetuned", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "wizard-rwkv-4-world-ctx32k.pth", @@ -859,7 +1001,8 @@ "Finetuned", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-7B-world-one.pth", @@ -878,7 +1021,8 @@ "RWKV-4", "Global" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "rwkv-world-one-novel-cot-ultrachat-novel-instructions.pth", @@ -897,7 +1041,8 @@ "RWKV-4", "Global" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "RWKV-world-novel-one-state-ultrachat-cot-tuned-Role-play-65k.pth", @@ -917,7 +1062,8 @@ "Global", "Role Play" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "RWKV-4-7B-world-one-novel-tuned-65k.pth", @@ -936,7 +1082,8 @@ "RWKV-4", "CN" ], - "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt" + "customTokenizer": "backend-python/rwkv_pip/rwkv_vocab_v20230424_special_token.txt", + "hide": true }, { "name": "RWKV-4-World-CHNtuned-7B-v1-20230709-ctx4096.pth", @@ -954,7 +1101,8 @@ "Official", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "Readflow-RWKV-4-World-CHNtuned-7B-v1-20230709-ctx32k.pth", @@ -972,7 +1120,8 @@ "Finetuned", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "novel-RWKV-4-World-CHNtuned-7B-v1-20230709-ctx32k.pth", @@ -990,7 +1139,8 @@ "Finetuned", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "chatgal-RWKV-4-World-CHNtuned-7B-v1-20230709-ctx32k-1000.pth", @@ -1008,7 +1158,8 @@ "Finetuned", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "chatgal-RWKV-4-World-CHNtuned-7B-v1-20230709-ctx32k-500.pth", @@ -1026,7 +1177,8 @@ "Finetuned", "RWKV-4", "CN" - ] + ], + "hide": true }, { "name": "RWKV-4-World-JPNtuned-7B-v1-20230718-ctx4096.pth", @@ -1044,7 +1196,8 @@ "Official", "RWKV-4", "JP" - ] + ], + "hide": true }, { "name": "RWKV-novel-4-World-7B-20230810-ctx128k.pth", @@ -1062,7 +1215,8 @@ "Finetuned", "RWKV-4", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-Novel-7B-v1-ChnEng-ChnPro-20230410-ctx4096.pth", @@ -1080,7 +1234,8 @@ "RWKV-4", "Raven", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-Novel-3B-v1-ChnEng-20230412-ctx4096.pth", @@ -1098,7 +1253,8 @@ "RWKV-4", "Raven", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-Novel-7B-v1-ChnEng-20230426-ctx8192.pth", @@ -1116,7 +1272,8 @@ "RWKV-4", "Raven", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-Novel-3B-v1-Chn-20230412-ctx4096.pth", @@ -1134,7 +1291,8 @@ "RWKV-4", "Raven", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-Novel-7B-v1-Chn-20230426-ctx8192.pth", @@ -1152,7 +1310,8 @@ "RWKV-4", "Raven", "Global" - ] + ], + "hide": true }, { "name": "RWKV-4-Raven-1B5-v11-Eng99%-Other1%-20230425-ctx4096.pth", @@ -1187,7 +1346,8 @@ "Official", "RWKV-4", "Raven" - ] + ], + "hide": true }, { "name": "RWKV-4-Raven-3B-v11-Eng99%-Other1%-20230425-ctx4096.pth", @@ -1222,7 +1382,8 @@ "Official", "RWKV-4", "Raven" - ] + ], + "hide": true }, { "name": "RWKV-4-Raven-3B-v11-Eng49%-Chn49%-Jpn1%-Other1%-20230429-ctx4096.pth", @@ -1259,7 +1420,8 @@ "RWKV-4", "Raven", "CN" - ] + ], + "hide": true }, { "name": "RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth", @@ -1294,7 +1456,8 @@ "Official", "RWKV-4", "Raven" - ] + ], + "hide": true }, { "name": "RWKV-4-Raven-7B-v10x-Eng49%-Chn50%-Other1%-20230423-ctx4096.pth", @@ -1350,7 +1513,8 @@ "RWKV-4", "Raven", "CN" - ] + ], + "hide": true }, { "name": "RWKV-4-Raven-14B-v11x-Eng99%-Other1%-20230501-ctx8192.pth", @@ -1385,7 +1549,8 @@ "Official", "RWKV-4", "Raven" - ] + ], + "hide": true }, { "name": "RWKV-4-MIDI-120M-v1-20230714-ctx4096.pth", diff --git a/wails.json b/wails.json index c6914bea..742219bf 100644 --- a/wails.json +++ b/wails.json @@ -9,5 +9,11 @@ "author": { "name": "josc146", "email": "josStorer@outlook.com" + }, + "Info": { + "companyName": "RWKV-Runner", + "productName": "RWKV-Runner", + "productVersion": "1.0.0", + "copyright": "Copyright © 2023 RWKV-Runner" } }