☰', elem_id='gr-hover')
+
+ with gr.Column(scale=10, elem_id='chat-input-container'):
+ shared.gradio['textbox'] = gr.MultimodalTextbox(label='', placeholder='Send a message', file_types=['text', '.pdf', 'image'], file_count="multiple", elem_id='chat-input', elem_classes=['add_scrollbar'])
+ shared.gradio['typing-dots'] = gr.HTML(value='
', label='typing', elem_id='typing-container')
+
+ with gr.Column(scale=1, elem_id='generate-stop-container'):
+ with gr.Row():
+ shared.gradio['Stop'] = gr.Button('Stop', elem_id='stop', visible=False)
+ shared.gradio['Generate'] = gr.Button('Send', elem_id='Generate', variant='primary')
+
+ # Hover menu buttons
+ with gr.Column(elem_id='chat-buttons'):
+ shared.gradio['Regenerate'] = gr.Button('Regenerate (Ctrl + Enter)', elem_id='Regenerate')
+ shared.gradio['Continue'] = gr.Button('Continue (Alt + Enter)', elem_id='Continue')
+ shared.gradio['Remove last'] = gr.Button('Remove last reply (Ctrl + Shift + Backspace)', elem_id='Remove-last')
+ shared.gradio['Impersonate'] = gr.Button('Impersonate (Ctrl + Shift + M)', elem_id='Impersonate')
+ shared.gradio['Send dummy message'] = gr.Button('Send dummy message')
+ shared.gradio['Send dummy reply'] = gr.Button('Send dummy reply')
+ shared.gradio['send-chat-to-notebook'] = gr.Button('Send to Notebook')
+ shared.gradio['show_controls'] = gr.Checkbox(value=shared.settings['show_controls'], label='Show controls (Ctrl+S)', elem_id='show-controls')
+
+ with gr.Row(elem_id='chat-controls', elem_classes=['pretty_scrollbar']):
+ with gr.Column():
+ with gr.Row():
+ shared.gradio['start_with'] = gr.Textbox(label='Start reply with', placeholder='Sure thing!', value=shared.settings['start_with'], elem_classes=['add_scrollbar'])
+
+ gr.HTML("")
+
+ shared.gradio['reasoning_effort'] = gr.Dropdown(value=shared.settings['reasoning_effort'], choices=['low', 'medium', 'high'], label='Reasoning effort', info='Used by GPT-OSS.')
+ shared.gradio['enable_thinking'] = gr.Checkbox(value=shared.settings['enable_thinking'], label='Enable thinking', info='Used by Seed-OSS and pre-2507 Qwen3.')
+
+ gr.HTML("")
+
+ shared.gradio['enable_web_search'] = gr.Checkbox(value=shared.settings.get('enable_web_search', False), label='Activate web search', elem_id='web-search')
+ with gr.Row(visible=shared.settings.get('enable_web_search', False)) as shared.gradio['web_search_row']:
+ shared.gradio['web_search_pages'] = gr.Number(value=shared.settings.get('web_search_pages', 3), precision=0, label='Number of pages to download', minimum=1, maximum=10)
+
+ gr.HTML("")
+
+ with gr.Row():
+ shared.gradio['mode'] = gr.Radio(choices=['instruct', 'chat-instruct', 'chat'], value=None, label='Mode', info='In instruct and chat-instruct modes, the template under Parameters > Instruction template is used.', elem_id='chat-mode')
+
+ with gr.Row():
+ shared.gradio['chat_style'] = gr.Dropdown(choices=utils.get_available_chat_styles(), label='Chat style', value=shared.settings['chat_style'], visible=shared.settings['mode'] != 'instruct')
+
+ with gr.Row():
+ shared.gradio['chat-instruct_command'] = gr.Textbox(value=shared.settings['chat-instruct_command'], lines=12, label='Command for chat-instruct mode', info='<|character|> and <|prompt|> get replaced with the bot name and the regular chat prompt respectively.', visible=shared.settings['mode'] == 'chat-instruct', elem_classes=['add_scrollbar'])
+
+ gr.HTML("")
+
+ with gr.Row():
+ shared.gradio['count_tokens'] = gr.Button('Count tokens', size='sm')
+
+ shared.gradio['token_display'] = gr.HTML(value='', elem_classes='token-display')
+
+ # Hidden elements for version navigation and editing
+ with gr.Row(visible=False):
+ shared.gradio['navigate_message_index'] = gr.Number(value=-1, precision=0, elem_id="Navigate-message-index")
+ shared.gradio['navigate_direction'] = gr.Textbox(value="", elem_id="Navigate-direction")
+ shared.gradio['navigate_message_role'] = gr.Textbox(value="", elem_id="Navigate-message-role")
+ shared.gradio['navigate_version'] = gr.Button(elem_id="Navigate-version")
+ shared.gradio['edit_message_index'] = gr.Number(value=-1, precision=0, elem_id="Edit-message-index")
+ shared.gradio['edit_message_text'] = gr.Textbox(value="", elem_id="Edit-message-text")
+ shared.gradio['edit_message_role'] = gr.Textbox(value="", elem_id="Edit-message-role")
+ shared.gradio['edit_message'] = gr.Button(elem_id="Edit-message")
+
+
+def create_character_settings_ui():
+ mu = shared.args.multi_user
+ with gr.Tab('Character', elem_id="character-tab"):
+ with gr.Row():
+ with gr.Column(scale=8):
+ with gr.Tab("Character"):
+ with gr.Row():
+ shared.gradio['character_menu'] = gr.Dropdown(value=shared.settings['character'], choices=utils.get_available_characters(), label='Character', elem_id='character-menu', info='Used in chat and chat-instruct modes.', elem_classes='slim-dropdown')
+ ui.create_refresh_button(shared.gradio['character_menu'], lambda: None, lambda: {'choices': utils.get_available_characters()}, 'refresh-button', interactive=not mu)
+ shared.gradio['save_character'] = gr.Button('💾', elem_classes='refresh-button', elem_id="save-character", interactive=not mu)
+ shared.gradio['delete_character'] = gr.Button('🗑️', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['restore_character'] = gr.Button('Restore character', elem_classes='refresh-button', interactive=True, elem_id='restore-character')
+
+ shared.gradio['name2'] = gr.Textbox(value=shared.settings['name2'], lines=1, label='Character\'s name')
+ shared.gradio['context'] = gr.Textbox(value=shared.settings['context'], lines=10, label='Context', elem_classes=['add_scrollbar'], elem_id="character-context")
+ shared.gradio['greeting'] = gr.Textbox(value=shared.settings['greeting'], lines=5, label='Greeting', elem_classes=['add_scrollbar'], elem_id="character-greeting")
+
+ with gr.Tab("User"):
+ shared.gradio['name1'] = gr.Textbox(value=shared.settings['name1'], lines=1, label='Name')
+ shared.gradio['user_bio'] = gr.Textbox(value=shared.settings['user_bio'], lines=10, label='Description', info='Here you can optionally write a description of yourself.', placeholder='{{user}}\'s personality: ...', elem_classes=['add_scrollbar'], elem_id="user-description")
+
+ with gr.Tab('Chat history'):
+ with gr.Row():
+ with gr.Column():
+ shared.gradio['save_chat_history'] = gr.Button(value='Save history')
+
+ with gr.Column():
+ shared.gradio['load_chat_history'] = gr.File(type='binary', file_types=['.json', '.txt'], label='Upload History JSON')
+
+ with gr.Tab('Upload character'):
+ with gr.Tab('YAML or JSON'):
+ with gr.Row():
+ shared.gradio['upload_json'] = gr.File(type='binary', file_types=['.json', '.yaml'], label='JSON or YAML File', interactive=not mu)
+ shared.gradio['upload_img_bot'] = gr.Image(type='filepath', label='Profile Picture (optional)', interactive=not mu)
+
+ shared.gradio['Submit character'] = gr.Button(value='Submit', interactive=False)
+
+ with gr.Tab('TavernAI PNG'):
+ with gr.Row():
+ with gr.Column():
+ shared.gradio['upload_img_tavern'] = gr.Image(type='filepath', label='TavernAI PNG File', elem_id='upload_img_tavern', interactive=not mu)
+ shared.gradio['tavern_json'] = gr.State()
+ with gr.Column():
+ shared.gradio['tavern_name'] = gr.Textbox(value='', lines=1, label='Name', interactive=False)
+ shared.gradio['tavern_desc'] = gr.Textbox(value='', lines=10, label='Description', interactive=False, elem_classes=['add_scrollbar'])
+
+ shared.gradio['Submit tavern character'] = gr.Button(value='Submit', interactive=False)
+
+ with gr.Column(scale=1):
+ shared.gradio['character_picture'] = gr.Image(label='Character picture', type='filepath', interactive=not mu)
+ shared.gradio['your_picture'] = gr.Image(label='Your picture', type='filepath', value=Image.open(Path('user_data/cache/pfp_me.png')) if Path('user_data/cache/pfp_me.png').exists() else None, interactive=not mu)
+
+
+def create_chat_settings_ui():
+ mu = shared.args.multi_user
+ with gr.Tab('Instruction template'):
+ with gr.Row():
+ with gr.Column():
+ with gr.Row():
+ shared.gradio['instruction_template'] = gr.Dropdown(choices=utils.get_available_instruction_templates(), label='Saved instruction templates', info="After selecting the template, click on \"Load\" to load and apply it.", value='None', elem_classes='slim-dropdown')
+ ui.create_refresh_button(shared.gradio['instruction_template'], lambda: None, lambda: {'choices': utils.get_available_instruction_templates()}, 'refresh-button', interactive=not mu)
+ shared.gradio['load_template'] = gr.Button("Load", elem_classes='refresh-button')
+ shared.gradio['save_template'] = gr.Button('💾', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['delete_template'] = gr.Button('🗑️ ', elem_classes='refresh-button', interactive=not mu)
+
+ with gr.Column():
+ pass
+
+ with gr.Row():
+ with gr.Column():
+ shared.gradio['instruction_template_str'] = gr.Textbox(value=shared.settings['instruction_template_str'], label='Instruction template', lines=24, info='This gets autodetected; you usually don\'t need to change it. Used in instruct and chat-instruct modes.', elem_classes=['add_scrollbar', 'monospace'], elem_id='instruction-template-str')
+ with gr.Row():
+ shared.gradio['send_instruction_to_notebook'] = gr.Button('Send to notebook', elem_classes=['small-button'])
+
+ with gr.Column():
+ shared.gradio['chat_template_str'] = gr.Textbox(value=shared.settings['chat_template_str'], label='Chat template', lines=22, elem_classes=['add_scrollbar', 'monospace'], info='Defines how the chat prompt in chat/chat-instruct modes is generated.', elem_id='chat-template-str')
+
+
+def create_event_handlers():
+
+ # Obsolete variables, kept for compatibility with old extensions
+ shared.input_params = gradio(inputs)
+ shared.reload_inputs = gradio(reload_arr)
+
+ # Morph HTML updates instead of updating everything
+ shared.gradio['display'].change(None, gradio('display'), None, js="(data) => handleMorphdomUpdate(data)")
+
+ shared.gradio['Generate'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda x: (x, {"text": "", "files": []}), gradio('textbox'), gradio('Chat input', 'textbox'), show_progress=False).then(
+ lambda: None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.add("_generating")').then(
+ chat.generate_chat_reply_wrapper, gradio(inputs), gradio('display', 'history'), show_progress=False).then(
+ None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.remove("_generating")').then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['textbox'].submit(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda x: (x, {"text": "", "files": []}), gradio('textbox'), gradio('Chat input', 'textbox'), show_progress=False).then(
+ lambda: None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.add("_generating")').then(
+ chat.generate_chat_reply_wrapper, gradio(inputs), gradio('display', 'history'), show_progress=False).then(
+ None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.remove("_generating")').then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Regenerate'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.add("_generating")').then(
+ partial(chat.generate_chat_reply_wrapper, regenerate=True), gradio(inputs), gradio('display', 'history'), show_progress=False).then(
+ None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.remove("_generating")').then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Continue'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.add("_generating")').then(
+ partial(chat.generate_chat_reply_wrapper, _continue=True), gradio(inputs), gradio('display', 'history'), show_progress=False).then(
+ None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.remove("_generating")').then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Impersonate'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda x: x, gradio('textbox'), gradio('Chat input'), show_progress=False).then(
+ lambda: None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.add("_generating")').then(
+ chat.impersonate_wrapper, gradio(inputs), gradio('textbox', 'display'), show_progress=False).then(
+ None, None, None, js='() => document.getElementById("chat").parentNode.parentNode.parentNode.classList.remove("_generating")').then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Send dummy message'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_send_dummy_message_click, gradio('textbox', 'interface_state'), gradio('history', 'display', 'textbox'), show_progress=False)
+
+ shared.gradio['Send dummy reply'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_send_dummy_reply_click, gradio('textbox', 'interface_state'), gradio('history', 'display', 'textbox'), show_progress=False)
+
+ shared.gradio['Remove last'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_remove_last_click, gradio('interface_state'), gradio('history', 'display', 'textbox'), show_progress=False)
+
+ shared.gradio['Stop'].click(
+ stop_everything_event, None, None, queue=False).then(
+ chat.redraw_html, gradio(reload_arr), gradio('display'), show_progress=False)
+
+ if not shared.args.multi_user:
+ shared.gradio['unique_id'].select(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_unique_id_select, gradio('interface_state'), gradio('history', 'display'), show_progress=False)
+
+ shared.gradio['Start new chat'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_start_new_chat_click, gradio('interface_state'), gradio('history', 'display', 'unique_id'), show_progress=False)
+
+ shared.gradio['delete_chat-confirm'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_delete_chat_confirm_click, gradio('interface_state'), gradio('history', 'display', 'unique_id'), show_progress=False)
+
+ shared.gradio['branch_chat'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_branch_chat_click, gradio('interface_state'), gradio('history', 'display', 'unique_id', 'branch_index'), show_progress=False)
+
+ shared.gradio['rename_chat'].click(chat.handle_rename_chat_click, None, gradio('rename_to', 'rename-row'), show_progress=False)
+ shared.gradio['rename_to-cancel'].click(lambda: gr.update(visible=False), None, gradio('rename-row'), show_progress=False)
+ shared.gradio['rename_to-confirm'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_rename_chat_confirm, gradio('rename_to', 'interface_state'), gradio('unique_id', 'rename-row'))
+
+ shared.gradio['rename_to'].submit(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_rename_chat_confirm, gradio('rename_to', 'interface_state'), gradio('unique_id', 'rename-row'), show_progress=False)
+
+ shared.gradio['search_chat'].change(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_search_chat_change, gradio('interface_state'), gradio('unique_id'), show_progress=False)
+
+ shared.gradio['load_chat_history'].upload(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_upload_chat_history, gradio('load_chat_history', 'interface_state'), gradio('history', 'display', 'unique_id'), show_progress=False).then(
+ None, None, None, js=f'() => {{{ui.switch_tabs_js}; switch_to_chat()}}')
+
+ shared.gradio['character_menu'].change(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_character_menu_change, gradio('interface_state'), gradio('history', 'display', 'name1', 'name2', 'character_picture', 'greeting', 'context', 'unique_id'), show_progress=False).then(
+ None, None, None, js=f'() => {{{ui.update_big_picture_js}; updateBigPicture()}}')
+
+ shared.gradio['character_picture'].change(chat.handle_character_picture_change, gradio('character_picture'), None, show_progress=False)
+
+ shared.gradio['mode'].change(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_mode_change, gradio('interface_state'), gradio('history', 'display', 'chat_style', 'chat-instruct_command', 'unique_id'), show_progress=False).then(
+ None, gradio('mode'), None, js="(mode) => {const characterContainer = document.getElementById('character-menu').parentNode.parentNode; const isInChatTab = document.querySelector('#chat-controls').contains(characterContainer); if (isInChatTab) { characterContainer.style.display = mode === 'instruct' ? 'none' : ''; } if (mode === 'instruct') document.querySelectorAll('.bigProfilePicture').forEach(el => el.remove());}")
+
+ shared.gradio['chat_style'].change(chat.redraw_html, gradio(reload_arr), gradio('display'), show_progress=False)
+
+ shared.gradio['navigate_version'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_navigate_version_click, gradio('interface_state'), gradio('history', 'display'), show_progress=False)
+
+ shared.gradio['edit_message'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_edit_message_click, gradio('interface_state'), gradio('history', 'display'), show_progress=False)
+
+ # Save/delete a character
+ shared.gradio['save_character'].click(chat.handle_save_character_click, gradio('name2'), gradio('save_character_filename', 'character_saver'), show_progress=False)
+ shared.gradio['delete_character'].click(lambda: gr.update(visible=True), None, gradio('character_deleter'), show_progress=False)
+ shared.gradio['load_template'].click(chat.handle_load_template_click, gradio('instruction_template'), gradio('instruction_template_str', 'instruction_template'), show_progress=False)
+ shared.gradio['save_template'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_save_template_click, gradio('instruction_template_str'), gradio('save_filename', 'save_root', 'save_contents', 'file_saver'), show_progress=False)
+
+ shared.gradio['restore_character'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.restore_character_for_ui, gradio('interface_state'), gradio('interface_state', 'name2', 'context', 'greeting', 'character_picture'), show_progress=False)
+
+ shared.gradio['delete_template'].click(chat.handle_delete_template_click, gradio('instruction_template'), gradio('delete_filename', 'delete_root', 'file_deleter'), show_progress=False)
+ shared.gradio['save_chat_history'].click(
+ lambda x: json.dumps(x, indent=4), gradio('history'), gradio('temporary_text')).then(
+ None, gradio('temporary_text', 'character_menu', 'mode'), None, js=f'(hist, char, mode) => {{{ui.save_files_js}; saveHistory(hist, char, mode)}}')
+
+ shared.gradio['Submit character'].click(
+ chat.upload_character, gradio('upload_json', 'upload_img_bot'), gradio('character_menu'), show_progress=False).then(
+ None, None, None, js=f'() => {{{ui.switch_tabs_js}; switch_to_character()}}')
+
+ shared.gradio['Submit tavern character'].click(
+ chat.upload_tavern_character, gradio('upload_img_tavern', 'tavern_json'), gradio('character_menu'), show_progress=False).then(
+ None, None, None, js=f'() => {{{ui.switch_tabs_js}; switch_to_character()}}')
+
+ shared.gradio['upload_json'].upload(lambda: gr.update(interactive=True), None, gradio('Submit character'))
+ shared.gradio['upload_json'].clear(lambda: gr.update(interactive=False), None, gradio('Submit character'))
+ shared.gradio['upload_img_tavern'].upload(chat.check_tavern_character, gradio('upload_img_tavern'), gradio('tavern_name', 'tavern_desc', 'tavern_json', 'Submit tavern character'), show_progress=False)
+ shared.gradio['upload_img_tavern'].clear(lambda: (None, None, None, gr.update(interactive=False)), None, gradio('tavern_name', 'tavern_desc', 'tavern_json', 'Submit tavern character'), show_progress=False)
+ shared.gradio['your_picture'].change(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_your_picture_change, gradio('your_picture', 'interface_state'), gradio('display'), show_progress=False)
+
+ shared.gradio['send_instruction_to_notebook'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_send_instruction_click, gradio('interface_state'), gradio('textbox-notebook', 'textbox-default', 'output_textbox'), show_progress=False).then(
+ None, None, None, js=f'() => {{{ui.switch_tabs_js}; switch_to_notebook()}}')
+
+ shared.gradio['send-chat-to-notebook'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.handle_send_chat_click, gradio('interface_state'), gradio('textbox-notebook', 'textbox-default', 'output_textbox'), show_progress=False).then(
+ None, None, None, js=f'() => {{{ui.switch_tabs_js}; switch_to_notebook()}}')
+
+ shared.gradio['show_controls'].change(None, gradio('show_controls'), None, js=f'(x) => {{{ui.show_controls_js}; toggle_controls(x)}}')
+
+ shared.gradio['count_tokens'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ chat.count_prompt_tokens, gradio('textbox', 'interface_state'), gradio('token_display'), show_progress=False)
+
+ shared.gradio['enable_web_search'].change(
+ lambda x: gr.update(visible=x),
+ gradio('enable_web_search'),
+ gradio('web_search_row')
+ )
diff --git a/modules/ui_default.py b/modules/ui_default.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0feae19479fd48773fc0ad1e9dc51ea89c2b7ab
--- /dev/null
+++ b/modules/ui_default.py
@@ -0,0 +1,215 @@
+from pathlib import Path
+
+import gradio as gr
+
+from modules import logits, shared, ui, utils
+from modules.prompts import count_tokens, load_prompt
+from modules.text_generation import (
+ generate_reply_wrapper,
+ get_token_ids,
+ stop_everything_event
+)
+from modules.ui_notebook import store_notebook_state_and_debounce
+from modules.utils import gradio
+
+inputs = ('textbox-default', 'interface_state')
+outputs = ('output_textbox', 'html-default')
+
+
+def create_ui():
+ mu = shared.args.multi_user
+ with gr.Row(visible=shared.settings['show_two_notebook_columns']) as shared.gradio['default-tab']:
+ with gr.Row():
+ with gr.Column():
+ with gr.Row():
+ shared.gradio['textbox-default'] = gr.Textbox(value="", lines=27, label='Input', elem_classes=['textbox_default', 'add_scrollbar'])
+ shared.gradio['token-counter-default'] = gr.HTML(value="
0", elem_id="default-token-counter")
+
+ with gr.Row():
+ shared.gradio['Continue-default'] = gr.Button('Continue')
+ shared.gradio['Stop-default'] = gr.Button('Stop', elem_id='stop', visible=False)
+ shared.gradio['Generate-default'] = gr.Button('Generate', variant='primary')
+
+ with gr.Row():
+ shared.gradio['prompt_menu-default'] = gr.Dropdown(choices=utils.get_available_prompts(), value=shared.settings['prompt-notebook'], label='Prompt', elem_classes='slim-dropdown')
+ ui.create_refresh_button(shared.gradio['prompt_menu-default'], lambda: None, lambda: {'choices': utils.get_available_prompts()}, 'refresh-button', interactive=not mu)
+ shared.gradio['new_prompt-default'] = gr.Button('New', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['rename_prompt-default'] = gr.Button('Rename', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['delete_prompt-default'] = gr.Button('🗑️', elem_classes='refresh-button', interactive=not mu)
+
+ # Rename elements (initially hidden)
+ shared.gradio['rename_prompt_to-default'] = gr.Textbox(label="New name", elem_classes=['no-background'], visible=False)
+ shared.gradio['rename_prompt-cancel-default'] = gr.Button('Cancel', elem_classes=['refresh-button'], visible=False)
+ shared.gradio['rename_prompt-confirm-default'] = gr.Button('Confirm', elem_classes=['refresh-button'], variant='primary', visible=False)
+
+ # Delete confirmation elements (initially hidden)
+ shared.gradio['delete_prompt-cancel-default'] = gr.Button('Cancel', elem_classes=['refresh-button'], visible=False)
+ shared.gradio['delete_prompt-confirm-default'] = gr.Button('Confirm', variant='stop', elem_classes=['refresh-button'], visible=False)
+
+ with gr.Column():
+ with gr.Tab('Raw'):
+ shared.gradio['output_textbox'] = gr.Textbox(lines=27, label='Output', elem_id='textbox-default', elem_classes=['textbox_default_output', 'add_scrollbar'])
+
+ with gr.Tab('Markdown'):
+ shared.gradio['markdown_render-default'] = gr.Button('Render')
+ shared.gradio['markdown-default'] = gr.Markdown()
+
+ with gr.Tab('HTML'):
+ shared.gradio['html-default'] = gr.HTML()
+
+ with gr.Tab('Logits'):
+ with gr.Row():
+ with gr.Column(scale=10):
+ shared.gradio['get_logits-default'] = gr.Button('Get next token probabilities')
+ with gr.Column(scale=1):
+ shared.gradio['use_samplers-default'] = gr.Checkbox(label='Use samplers', value=True, elem_classes=['no-background'])
+
+ with gr.Row():
+ shared.gradio['logits-default'] = gr.Textbox(lines=23, label='Output', elem_classes=['textbox_logits', 'add_scrollbar'])
+ shared.gradio['logits-default-previous'] = gr.Textbox(lines=23, label='Previous output', elem_classes=['textbox_logits', 'add_scrollbar'])
+
+ with gr.Tab('Tokens'):
+ shared.gradio['get_tokens-default'] = gr.Button('Get token IDs for the input')
+ shared.gradio['tokens-default'] = gr.Textbox(lines=23, label='Tokens', elem_classes=['textbox_logits', 'add_scrollbar', 'monospace'])
+
+
+def create_event_handlers():
+ shared.gradio['Generate-default'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: [gr.update(visible=True), gr.update(visible=False)], None, gradio('Stop-default', 'Generate-default')).then(
+ generate_reply_wrapper, gradio('textbox-default', 'interface_state'), gradio(outputs), show_progress=False).then(
+ lambda state, left, right: state.update({'textbox-default': left, 'output_textbox': right}), gradio('interface_state', 'textbox-default', 'output_textbox'), None).then(
+ lambda: [gr.update(visible=False), gr.update(visible=True)], None, gradio('Stop-default', 'Generate-default')).then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['textbox-default'].submit(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: [gr.update(visible=True), gr.update(visible=False)], None, gradio('Stop-default', 'Generate-default')).then(
+ generate_reply_wrapper, gradio('textbox-default', 'interface_state'), gradio(outputs), show_progress=False).then(
+ lambda state, left, right: state.update({'textbox-default': left, 'output_textbox': right}), gradio('interface_state', 'textbox-default', 'output_textbox'), None).then(
+ lambda: [gr.update(visible=False), gr.update(visible=True)], None, gradio('Stop-default', 'Generate-default')).then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Continue-default'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: [gr.update(visible=True), gr.update(visible=False)], None, gradio('Stop-default', 'Generate-default')).then(
+ generate_reply_wrapper, gradio('output_textbox', 'interface_state'), gradio(outputs), show_progress=False).then(
+ lambda state, left, right: state.update({'textbox-default': left, 'output_textbox': right}), gradio('interface_state', 'textbox-default', 'output_textbox'), None).then(
+ lambda: [gr.update(visible=False), gr.update(visible=True)], None, gradio('Stop-default', 'Generate-default')).then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Stop-default'].click(stop_everything_event, None, None, queue=False)
+ shared.gradio['markdown_render-default'].click(lambda x: x, gradio('output_textbox'), gradio('markdown-default'), queue=False)
+ shared.gradio['prompt_menu-default'].change(lambda x: (load_prompt(x), ""), gradio('prompt_menu-default'), gradio('textbox-default', 'output_textbox'), show_progress=False)
+ shared.gradio['new_prompt-default'].click(handle_new_prompt, None, gradio('prompt_menu-default'), show_progress=False)
+
+ # Input change handler to save input (reusing notebook's debounced saving)
+ shared.gradio['textbox-default'].change(
+ store_notebook_state_and_debounce,
+ gradio('textbox-default', 'prompt_menu-default'),
+ None,
+ show_progress=False
+ )
+
+ shared.gradio['delete_prompt-default'].click(
+ lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)],
+ None,
+ gradio('delete_prompt-default', 'delete_prompt-cancel-default', 'delete_prompt-confirm-default'),
+ show_progress=False)
+
+ shared.gradio['delete_prompt-cancel-default'].click(
+ lambda: [gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)],
+ None,
+ gradio('delete_prompt-default', 'delete_prompt-cancel-default', 'delete_prompt-confirm-default'),
+ show_progress=False)
+
+ shared.gradio['delete_prompt-confirm-default'].click(
+ handle_delete_prompt_confirm_default,
+ gradio('prompt_menu-default'),
+ gradio('prompt_menu-default', 'delete_prompt-default', 'delete_prompt-cancel-default', 'delete_prompt-confirm-default'),
+ show_progress=False)
+
+ shared.gradio['rename_prompt-default'].click(
+ handle_rename_prompt_click_default,
+ gradio('prompt_menu-default'),
+ gradio('rename_prompt_to-default', 'rename_prompt-default', 'rename_prompt-cancel-default', 'rename_prompt-confirm-default'),
+ show_progress=False)
+
+ shared.gradio['rename_prompt-cancel-default'].click(
+ lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)],
+ None,
+ gradio('rename_prompt_to-default', 'rename_prompt-default', 'rename_prompt-cancel-default', 'rename_prompt-confirm-default'),
+ show_progress=False)
+
+ shared.gradio['rename_prompt-confirm-default'].click(
+ handle_rename_prompt_confirm_default,
+ gradio('rename_prompt_to-default', 'prompt_menu-default'),
+ gradio('prompt_menu-default', 'rename_prompt_to-default', 'rename_prompt-default', 'rename_prompt-cancel-default', 'rename_prompt-confirm-default'),
+ show_progress=False)
+
+ shared.gradio['textbox-default'].change(lambda x: f"
{count_tokens(x)}", gradio('textbox-default'), gradio('token-counter-default'), show_progress=False)
+ shared.gradio['get_logits-default'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ logits.get_next_logits, gradio('textbox-default', 'interface_state', 'use_samplers-default', 'logits-default'), gradio('logits-default', 'logits-default-previous'), show_progress=False)
+
+ shared.gradio['get_tokens-default'].click(get_token_ids, gradio('textbox-default'), gradio('tokens-default'), show_progress=False)
+
+
+def handle_new_prompt():
+ new_name = utils.current_time()
+
+ # Create the new prompt file
+ prompt_path = Path("user_data/logs/notebook") / f"{new_name}.txt"
+ prompt_path.parent.mkdir(parents=True, exist_ok=True)
+ prompt_path.write_text("In this story,", encoding='utf-8')
+
+ return gr.update(choices=utils.get_available_prompts(), value=new_name)
+
+
+def handle_delete_prompt_confirm_default(prompt_name):
+ available_prompts = utils.get_available_prompts()
+ current_index = available_prompts.index(prompt_name) if prompt_name in available_prompts else 0
+
+ (Path("user_data/logs/notebook") / f"{prompt_name}.txt").unlink(missing_ok=True)
+ available_prompts = utils.get_available_prompts()
+
+ if available_prompts:
+ new_value = available_prompts[min(current_index, len(available_prompts) - 1)]
+ else:
+ new_value = utils.current_time()
+ Path("user_data/logs/notebook").mkdir(parents=True, exist_ok=True)
+ (Path("user_data/logs/notebook") / f"{new_value}.txt").write_text("In this story,")
+ available_prompts = [new_value]
+
+ return [
+ gr.update(choices=available_prompts, value=new_value),
+ gr.update(visible=True),
+ gr.update(visible=False),
+ gr.update(visible=False)
+ ]
+
+
+def handle_rename_prompt_click_default(current_name):
+ return [
+ gr.update(value=current_name, visible=True),
+ gr.update(visible=False),
+ gr.update(visible=True),
+ gr.update(visible=True)
+ ]
+
+
+def handle_rename_prompt_confirm_default(new_name, current_name):
+ old_path = Path("user_data/logs/notebook") / f"{current_name}.txt"
+ new_path = Path("user_data/logs/notebook") / f"{new_name}.txt"
+
+ if old_path.exists() and not new_path.exists():
+ old_path.rename(new_path)
+
+ available_prompts = utils.get_available_prompts()
+ return [
+ gr.update(choices=available_prompts, value=new_name),
+ gr.update(visible=False),
+ gr.update(visible=True),
+ gr.update(visible=False),
+ gr.update(visible=False)
+ ]
diff --git a/modules/ui_file_saving.py b/modules/ui_file_saving.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1f9379b5aed59d839d4363310069c6d91f30d8b
--- /dev/null
+++ b/modules/ui_file_saving.py
@@ -0,0 +1,167 @@
+import traceback
+
+import gradio as gr
+
+from modules import chat, presets, shared, ui, utils
+from modules.utils import gradio
+
+
+def create_ui():
+ mu = shared.args.multi_user
+
+ # Text file saver
+ with gr.Group(visible=False, elem_classes='file-saver') as shared.gradio['file_saver']:
+ shared.gradio['save_filename'] = gr.Textbox(lines=1, label='File name')
+ shared.gradio['save_root'] = gr.Textbox(lines=1, label='File folder', info='For reference. Unchangeable.', interactive=False)
+ shared.gradio['save_contents'] = gr.Textbox(lines=10, label='File contents')
+ with gr.Row():
+ shared.gradio['save_cancel'] = gr.Button('Cancel', elem_classes="small-button")
+ shared.gradio['save_confirm'] = gr.Button('Save', elem_classes="small-button", variant='primary', interactive=not mu)
+
+ # Text file deleter
+ with gr.Group(visible=False, elem_classes='file-saver') as shared.gradio['file_deleter']:
+ shared.gradio['delete_filename'] = gr.Textbox(lines=1, label='File name')
+ shared.gradio['delete_root'] = gr.Textbox(lines=1, label='File folder', info='For reference. Unchangeable.', interactive=False)
+ with gr.Row():
+ shared.gradio['delete_cancel'] = gr.Button('Cancel', elem_classes="small-button")
+ shared.gradio['delete_confirm'] = gr.Button('Delete', elem_classes="small-button", variant='stop', interactive=not mu)
+
+ # Character saver/deleter
+ with gr.Group(visible=False, elem_classes='file-saver') as shared.gradio['character_saver']:
+ shared.gradio['save_character_filename'] = gr.Textbox(lines=1, label='File name', info='The character will be saved to your user_data/characters folder with this base filename.')
+ with gr.Row():
+ shared.gradio['save_character_cancel'] = gr.Button('Cancel', elem_classes="small-button")
+ shared.gradio['save_character_confirm'] = gr.Button('Save', elem_classes="small-button", variant='primary', interactive=not mu)
+
+ with gr.Group(visible=False, elem_classes='file-saver') as shared.gradio['character_deleter']:
+ gr.Markdown('Confirm the character deletion?')
+ with gr.Row():
+ shared.gradio['delete_character_cancel'] = gr.Button('Cancel', elem_classes="small-button")
+ shared.gradio['delete_character_confirm'] = gr.Button('Delete', elem_classes="small-button", variant='stop', interactive=not mu)
+
+ # Preset saver
+ with gr.Group(visible=False, elem_classes='file-saver') as shared.gradio['preset_saver']:
+ shared.gradio['save_preset_filename'] = gr.Textbox(lines=1, label='File name', info='The preset will be saved to your user_data/presets folder with this base filename.')
+ shared.gradio['save_preset_contents'] = gr.Textbox(lines=10, label='File contents')
+ with gr.Row():
+ shared.gradio['save_preset_cancel'] = gr.Button('Cancel', elem_classes="small-button")
+ shared.gradio['save_preset_confirm'] = gr.Button('Save', elem_classes="small-button", variant='primary', interactive=not mu)
+
+
+def create_event_handlers():
+ shared.gradio['save_preset'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ handle_save_preset_click, gradio('interface_state'), gradio('save_preset_contents', 'save_preset_filename', 'preset_saver'), show_progress=False)
+
+ shared.gradio['delete_preset'].click(handle_delete_preset_click, gradio('preset_menu'), gradio('delete_filename', 'delete_root', 'file_deleter'), show_progress=False)
+ shared.gradio['save_grammar'].click(handle_save_grammar_click, gradio('grammar_string'), gradio('save_contents', 'save_filename', 'save_root', 'file_saver'), show_progress=False)
+ shared.gradio['delete_grammar'].click(handle_delete_grammar_click, gradio('grammar_file'), gradio('delete_filename', 'delete_root', 'file_deleter'), show_progress=False)
+
+ shared.gradio['save_preset_confirm'].click(handle_save_preset_confirm_click, gradio('save_preset_filename', 'save_preset_contents'), gradio('preset_menu', 'preset_saver'), show_progress=False)
+ shared.gradio['save_confirm'].click(handle_save_confirm_click, gradio('save_root', 'save_filename', 'save_contents'), gradio('file_saver'), show_progress=False)
+ shared.gradio['delete_confirm'].click(handle_delete_confirm_click, gradio('delete_root', 'delete_filename'), gradio('file_deleter'), show_progress=False)
+ shared.gradio['save_character_confirm'].click(handle_save_character_confirm_click, gradio('name2', 'greeting', 'context', 'character_picture', 'save_character_filename'), gradio('character_menu', 'character_saver'), show_progress=False)
+ shared.gradio['delete_character_confirm'].click(handle_delete_character_confirm_click, gradio('character_menu'), gradio('character_menu', 'character_deleter'), show_progress=False)
+
+ shared.gradio['save_preset_cancel'].click(lambda: gr.update(visible=False), None, gradio('preset_saver'), show_progress=False)
+ shared.gradio['save_cancel'].click(lambda: gr.update(visible=False), None, gradio('file_saver'))
+ shared.gradio['delete_cancel'].click(lambda: gr.update(visible=False), None, gradio('file_deleter'))
+ shared.gradio['save_character_cancel'].click(lambda: gr.update(visible=False), None, gradio('character_saver'), show_progress=False)
+ shared.gradio['delete_character_cancel'].click(lambda: gr.update(visible=False), None, gradio('character_deleter'), show_progress=False)
+
+
+def handle_save_preset_confirm_click(filename, contents):
+ try:
+ utils.save_file(f"user_data/presets/{filename}.yaml", contents)
+ available_presets = utils.get_available_presets()
+ output = gr.update(choices=available_presets, value=filename)
+ except Exception:
+ output = gr.update()
+ traceback.print_exc()
+
+ return [
+ output,
+ gr.update(visible=False)
+ ]
+
+
+def handle_save_confirm_click(root, filename, contents):
+ try:
+ utils.save_file(root + filename, contents)
+ except Exception:
+ traceback.print_exc()
+
+ return gr.update(visible=False)
+
+
+def handle_delete_confirm_click(root, filename):
+ try:
+ utils.delete_file(root + filename)
+ except Exception:
+ traceback.print_exc()
+
+ return gr.update(visible=False)
+
+
+def handle_save_character_confirm_click(name2, greeting, context, character_picture, filename):
+ try:
+ chat.save_character(name2, greeting, context, character_picture, filename)
+ available_characters = utils.get_available_characters()
+ output = gr.update(choices=available_characters, value=filename)
+ except Exception:
+ output = gr.update()
+ traceback.print_exc()
+
+ return [
+ output,
+ gr.update(visible=False)
+ ]
+
+
+def handle_delete_character_confirm_click(character):
+ try:
+ index = str(utils.get_available_characters().index(character))
+ chat.delete_character(character)
+ output = chat.update_character_menu_after_deletion(index)
+ except Exception:
+ output = gr.update()
+ traceback.print_exc()
+
+ return [
+ output,
+ gr.update(visible=False)
+ ]
+
+
+def handle_save_preset_click(state):
+ contents = presets.generate_preset_yaml(state)
+ return [
+ contents,
+ "My Preset",
+ gr.update(visible=True)
+ ]
+
+
+def handle_delete_preset_click(preset):
+ return [
+ f"{preset}.yaml",
+ "user_data/presets/",
+ gr.update(visible=True)
+ ]
+
+
+def handle_save_grammar_click(grammar_string):
+ return [
+ grammar_string,
+ "My Fancy Grammar.gbnf",
+ "user_data/grammars/",
+ gr.update(visible=True)
+ ]
+
+
+def handle_delete_grammar_click(grammar_file):
+ return [
+ grammar_file,
+ "user_data/grammars/",
+ gr.update(visible=True)
+ ]
diff --git a/modules/ui_model_menu.py b/modules/ui_model_menu.py
new file mode 100644
index 0000000000000000000000000000000000000000..729700d473362fda8c5de19f0ea5d23d9586b276
--- /dev/null
+++ b/modules/ui_model_menu.py
@@ -0,0 +1,435 @@
+import importlib
+import math
+import queue
+import threading
+import traceback
+from functools import partial
+from pathlib import Path
+
+import gradio as gr
+
+from modules import loaders, shared, ui, utils
+from modules.logging_colors import logger
+from modules.LoRA import add_lora_to_model
+from modules.models import load_model, unload_model
+from modules.models_settings import (
+ apply_model_settings_to_state,
+ get_model_metadata,
+ save_instruction_template,
+ save_model_settings,
+ update_gpu_layers_and_vram,
+ update_model_parameters
+)
+from modules.utils import gradio
+
+
+def create_ui():
+ mu = shared.args.multi_user
+
+ with gr.Tab("Model", elem_id="model-tab"):
+ with gr.Row():
+ with gr.Column():
+ with gr.Row():
+ shared.gradio['model_menu'] = gr.Dropdown(choices=utils.get_available_models(), value=lambda: shared.model_name, label='Model', elem_classes='slim-dropdown', interactive=not mu)
+ ui.create_refresh_button(shared.gradio['model_menu'], lambda: None, lambda: {'choices': utils.get_available_models()}, 'refresh-button', interactive=not mu)
+ shared.gradio['load_model'] = gr.Button("Load", elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['unload_model'] = gr.Button("Unload", elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['save_model_settings'] = gr.Button("Save settings", elem_classes='refresh-button', interactive=not mu)
+
+ shared.gradio['loader'] = gr.Dropdown(label="Model loader", choices=loaders.loaders_and_params.keys() if not shared.args.portable else ['llama.cpp'], value=None)
+ with gr.Blocks():
+ gr.Markdown("## Main options")
+ with gr.Row():
+ with gr.Column():
+ shared.gradio['gpu_layers'] = gr.Slider(label="gpu-layers", minimum=0, maximum=get_initial_gpu_layers_max(), step=1, value=shared.args.gpu_layers, info='Must be greater than 0 for the GPU to be used. ⚠️ Lower this value if you can\'t load the model.')
+ shared.gradio['ctx_size'] = gr.Slider(label='ctx-size', minimum=256, maximum=131072, step=256, value=shared.args.ctx_size, info='Context length. Common values: 4096, 8192, 16384, 32768, 65536, 131072.')
+ shared.gradio['gpu_split'] = gr.Textbox(label='gpu-split', info='Comma-separated list of VRAM (in GB) to use per GPU. Example: 20,7,7')
+ shared.gradio['attn_implementation'] = gr.Dropdown(label="attn-implementation", choices=['sdpa', 'eager', 'flash_attention_2'], value=shared.args.attn_implementation, info='Attention implementation.')
+ shared.gradio['cache_type'] = gr.Dropdown(label="cache-type", choices=['fp16', 'q8_0', 'q4_0', 'fp8', 'q8', 'q7', 'q6', 'q5', 'q4', 'q3', 'q2'], value=shared.args.cache_type, allow_custom_value=True, info='Valid options: llama.cpp - fp16, q8_0, q4_0; ExLlamaV2 - fp16, fp8, q8, q6, q4; ExLlamaV3 - fp16, q2 to q8. For ExLlamaV3, you can type custom combinations for separate k/v bits (e.g. q4_q8).')
+ shared.gradio['tp_backend'] = gr.Dropdown(label="tp-backend", choices=['native', 'nccl'], value=shared.args.tp_backend, info='The backend for tensor parallelism.')
+
+ with gr.Column():
+ shared.gradio['vram_info'] = gr.HTML(value=get_initial_vram_info())
+ shared.gradio['streaming_llm'] = gr.Checkbox(label="streaming-llm", value=shared.args.streaming_llm, info='Activate StreamingLLM to avoid re-evaluating the entire prompt when old messages are removed.')
+ shared.gradio['load_in_8bit'] = gr.Checkbox(label="load-in-8bit", value=shared.args.load_in_8bit)
+ shared.gradio['load_in_4bit'] = gr.Checkbox(label="load-in-4bit", value=shared.args.load_in_4bit)
+ shared.gradio['use_double_quant'] = gr.Checkbox(label="use_double_quant", value=shared.args.use_double_quant, info='Used by load-in-4bit.')
+ shared.gradio['autosplit'] = gr.Checkbox(label="autosplit", value=shared.args.autosplit, info='Automatically split the model tensors across the available GPUs.')
+ shared.gradio['enable_tp'] = gr.Checkbox(label="enable_tp", value=shared.args.enable_tp, info='Enable tensor parallelism (TP).')
+ shared.gradio['cpp_runner'] = gr.Checkbox(label="cpp-runner", value=shared.args.cpp_runner, info='Enable inference with ModelRunnerCpp, which is faster than the default ModelRunner.')
+ shared.gradio['trust_remote_code'] = gr.Checkbox(label="trust-remote-code", value=shared.args.trust_remote_code, info='Set trust_remote_code=True while loading the tokenizer/model. To enable this option, start the web UI with the --trust-remote-code flag.', interactive=shared.args.trust_remote_code)
+ shared.gradio['tensorrt_llm_info'] = gr.Markdown('* TensorRT-LLM has to be installed manually in a separate Python 3.10 environment at the moment. For a guide, consult the description of [this PR](https://github.com/oobabooga/text-generation-webui/pull/5715). \n\n* `ctx_size` is only used when `cpp-runner` is checked.\n\n* `cpp_runner` does not support streaming at the moment.')
+
+ # Multimodal
+ with gr.Accordion("Multimodal (vision)", open=False, elem_classes='tgw-accordion') as shared.gradio['mmproj_accordion']:
+ with gr.Row():
+ shared.gradio['mmproj'] = gr.Dropdown(label="mmproj file", choices=utils.get_available_mmproj(), value=lambda: shared.args.mmproj or 'None', elem_classes='slim-dropdown', info='Select a file that matches your model. Must be placed in user_data/mmproj/', interactive=not mu)
+ ui.create_refresh_button(shared.gradio['mmproj'], lambda: None, lambda: {'choices': utils.get_available_mmproj()}, 'refresh-button', interactive=not mu)
+
+ # Speculative decoding
+ with gr.Accordion("Speculative decoding", open=False, elem_classes='tgw-accordion') as shared.gradio['speculative_decoding_accordion']:
+ with gr.Row():
+ shared.gradio['model_draft'] = gr.Dropdown(label="model-draft", choices=['None'] + utils.get_available_models(), value=lambda: shared.args.model_draft, elem_classes='slim-dropdown', info='Draft model. Speculative decoding only works with models sharing the same vocabulary (e.g., same model family).', interactive=not mu)
+ ui.create_refresh_button(shared.gradio['model_draft'], lambda: None, lambda: {'choices': ['None'] + utils.get_available_models()}, 'refresh-button', interactive=not mu)
+
+ shared.gradio['gpu_layers_draft'] = gr.Slider(label="gpu-layers-draft", minimum=0, maximum=256, value=shared.args.gpu_layers_draft, info='Number of layers to offload to the GPU for the draft model.')
+ shared.gradio['draft_max'] = gr.Number(label="draft-max", precision=0, step=1, value=shared.args.draft_max, info='Number of tokens to draft for speculative decoding. Recommended value: 4.')
+ shared.gradio['device_draft'] = gr.Textbox(label="device-draft", value=shared.args.device_draft, info='Comma-separated list of devices to use for offloading the draft model. Example: CUDA0,CUDA1')
+ shared.gradio['ctx_size_draft'] = gr.Number(label="ctx-size-draft", precision=0, step=256, value=shared.args.ctx_size_draft, info='Size of the prompt context for the draft model. If 0, uses the same as the main model.')
+
+ gr.Markdown("## Other options")
+ with gr.Accordion("See more options", open=False, elem_classes='tgw-accordion'):
+ with gr.Row():
+ with gr.Column():
+ shared.gradio['threads'] = gr.Slider(label="threads", minimum=0, step=1, maximum=256, value=shared.args.threads)
+ shared.gradio['threads_batch'] = gr.Slider(label="threads_batch", minimum=0, step=1, maximum=256, value=shared.args.threads_batch)
+ shared.gradio['batch_size'] = gr.Slider(label="batch_size", minimum=1, maximum=4096, step=1, value=shared.args.batch_size)
+ shared.gradio['tensor_split'] = gr.Textbox(label='tensor_split', info='List of proportions to split the model across multiple GPUs. Example: 60,40')
+ shared.gradio['extra_flags'] = gr.Textbox(label='extra-flags', info='Additional flags to pass to llama-server. Format: "flag1=value1,flag2,flag3=value3". Example: "override-tensor=exps=CPU"', value=shared.args.extra_flags)
+ shared.gradio['cpu_memory'] = gr.Number(label="Maximum CPU memory in GiB. Use this for CPU offloading.", value=shared.args.cpu_memory)
+ shared.gradio['alpha_value'] = gr.Number(label='alpha_value', value=shared.args.alpha_value, precision=2, info='Positional embeddings alpha factor for NTK RoPE scaling. Recommended values (NTKv1): 1.75 for 1.5x context, 2.5 for 2x context. Use either this or compress_pos_emb, not both.')
+ shared.gradio['rope_freq_base'] = gr.Number(label='rope_freq_base', value=shared.args.rope_freq_base, precision=0, info='Positional embeddings frequency base for NTK RoPE scaling. Related to alpha_value by rope_freq_base = 10000 * alpha_value ^ (64 / 63). 0 = from model.')
+ shared.gradio['compress_pos_emb'] = gr.Number(label='compress_pos_emb', value=shared.args.compress_pos_emb, precision=2, info='Positional embeddings compression factor. Should be set to (context length) / (model\'s original context length). Equal to 1/rope_freq_scale.')
+ shared.gradio['compute_dtype'] = gr.Dropdown(label="compute_dtype", choices=["bfloat16", "float16", "float32"], value=shared.args.compute_dtype, info='Used by load-in-4bit.')
+ shared.gradio['quant_type'] = gr.Dropdown(label="quant_type", choices=["nf4", "fp4"], value=shared.args.quant_type, info='Used by load-in-4bit.')
+ shared.gradio['num_experts_per_token'] = gr.Number(label="Number of experts per token", value=shared.args.num_experts_per_token, info='Only applies to MoE models like Mixtral.')
+
+ with gr.Column():
+ shared.gradio['cpu'] = gr.Checkbox(label="cpu", value=shared.args.cpu, info='llama.cpp: Use llama-cpp-python compiled without GPU acceleration. Transformers: use PyTorch in CPU mode.')
+ shared.gradio['disk'] = gr.Checkbox(label="disk", value=shared.args.disk)
+ shared.gradio['row_split'] = gr.Checkbox(label="row_split", value=shared.args.row_split, info='Split the model by rows across GPUs. This may improve multi-gpu performance.')
+ shared.gradio['no_kv_offload'] = gr.Checkbox(label="no_kv_offload", value=shared.args.no_kv_offload, info='Do not offload the K, Q, V to the GPU. This saves VRAM but reduces the performance.')
+ shared.gradio['no_mmap'] = gr.Checkbox(label="no-mmap", value=shared.args.no_mmap)
+ shared.gradio['mlock'] = gr.Checkbox(label="mlock", value=shared.args.mlock)
+ shared.gradio['numa'] = gr.Checkbox(label="numa", value=shared.args.numa, info='NUMA support can help on some systems with non-uniform memory access.')
+ shared.gradio['bf16'] = gr.Checkbox(label="bf16", value=shared.args.bf16)
+ shared.gradio['no_flash_attn'] = gr.Checkbox(label="no_flash_attn", value=shared.args.no_flash_attn)
+ shared.gradio['no_xformers'] = gr.Checkbox(label="no_xformers", value=shared.args.no_xformers)
+ shared.gradio['no_sdpa'] = gr.Checkbox(label="no_sdpa", value=shared.args.no_sdpa)
+ shared.gradio['cfg_cache'] = gr.Checkbox(label="cfg-cache", value=shared.args.cfg_cache, info='Necessary to use CFG with this loader.')
+ shared.gradio['no_use_fast'] = gr.Checkbox(label="no_use_fast", value=shared.args.no_use_fast, info='Set use_fast=False while loading the tokenizer.')
+ if not shared.args.portable:
+ with gr.Row():
+ shared.gradio['lora_menu'] = gr.Dropdown(multiselect=True, choices=utils.get_available_loras(), value=shared.lora_names, label='LoRA(s)', elem_classes='slim-dropdown', interactive=not mu)
+ ui.create_refresh_button(shared.gradio['lora_menu'], lambda: None, lambda: {'choices': utils.get_available_loras(), 'value': shared.lora_names}, 'refresh-button', interactive=not mu)
+ shared.gradio['lora_menu_apply'] = gr.Button(value='Apply LoRAs', elem_classes='refresh-button', interactive=not mu)
+
+ with gr.Column():
+ with gr.Tab("Download"):
+ shared.gradio['custom_model_menu'] = gr.Textbox(label="Download model or LoRA", info="Enter the Hugging Face username/model path, for instance: facebook/galactica-125m. To specify a branch, add it at the end after a \":\" character like this: facebook/galactica-125m:main. To download a single file, enter its name in the second box.", interactive=not mu)
+ shared.gradio['download_specific_file'] = gr.Textbox(placeholder="File name (for GGUF models)", show_label=False, max_lines=1, interactive=not mu)
+ with gr.Row():
+ shared.gradio['download_model_button'] = gr.Button("Download", variant='primary', interactive=not mu)
+ shared.gradio['get_file_list'] = gr.Button("Get file list", interactive=not mu)
+
+ with gr.Tab("Customize instruction template"):
+ with gr.Row():
+ shared.gradio['customized_template'] = gr.Dropdown(choices=utils.get_available_instruction_templates(), value='None', label='Select the desired instruction template', elem_classes='slim-dropdown')
+ ui.create_refresh_button(shared.gradio['customized_template'], lambda: None, lambda: {'choices': utils.get_available_instruction_templates()}, 'refresh-button', interactive=not mu)
+
+ shared.gradio['customized_template_submit'] = gr.Button("Submit", variant="primary", interactive=not mu)
+ gr.Markdown("This allows you to set a customized template for the model currently selected in the \"Model loader\" menu. Whenever the model gets loaded, this template will be used in place of the template specified in the model's medatada, which sometimes is wrong.")
+
+ with gr.Row():
+ shared.gradio['model_status'] = gr.Markdown('No model is loaded' if shared.model_name == 'None' else 'Ready')
+
+
+def create_event_handlers():
+ mu = shared.args.multi_user
+ if mu:
+ return
+
+ shared.gradio['loader'].change(loaders.make_loader_params_visible, gradio('loader'), gradio(loaders.get_all_params()), show_progress=False)
+
+ # In this event handler, the interface state is read and updated
+ # with the model defaults (if any), and then the model is loaded
+ shared.gradio['model_menu'].change(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ handle_load_model_event_initial, gradio('model_menu', 'interface_state'), gradio(ui.list_interface_input_elements()) + gradio('interface_state') + gradio('vram_info'), show_progress=False).then(
+ partial(load_model_wrapper, autoload=False), gradio('model_menu', 'loader'), gradio('model_status'), show_progress=True).success(
+ handle_load_model_event_final, gradio('truncation_length', 'loader', 'interface_state'), gradio('truncation_length', 'filter_by_loader'), show_progress=False)
+
+ shared.gradio['load_model'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ update_model_parameters, gradio('interface_state'), None).then(
+ partial(load_model_wrapper, autoload=True), gradio('model_menu', 'loader'), gradio('model_status'), show_progress=True).success(
+ handle_load_model_event_final, gradio('truncation_length', 'loader', 'interface_state'), gradio('truncation_length', 'filter_by_loader'), show_progress=False)
+
+ shared.gradio['unload_model'].click(handle_unload_model_click, None, gradio('model_status'), show_progress=False).then(
+ partial(update_gpu_layers_and_vram, auto_adjust=True), gradio('loader', 'model_menu', 'gpu_layers', 'ctx_size', 'cache_type'), gradio('vram_info', 'gpu_layers'), show_progress=False)
+
+ shared.gradio['save_model_settings'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ save_model_settings, gradio('model_menu', 'interface_state'), gradio('model_status'), show_progress=False)
+
+ # For ctx_size and cache_type - auto-adjust GPU layers
+ for param in ['ctx_size', 'cache_type']:
+ shared.gradio[param].change(
+ partial(update_gpu_layers_and_vram, auto_adjust=True),
+ gradio('loader', 'model_menu', 'gpu_layers', 'ctx_size', 'cache_type'),
+ gradio('vram_info', 'gpu_layers'), show_progress=False)
+
+ # For manual gpu_layers changes - only update VRAM
+ shared.gradio['gpu_layers'].change(
+ partial(update_gpu_layers_and_vram, auto_adjust=False),
+ gradio('loader', 'model_menu', 'gpu_layers', 'ctx_size', 'cache_type'),
+ gradio('vram_info'), show_progress=False)
+
+ if not shared.args.portable:
+ shared.gradio['lora_menu_apply'].click(load_lora_wrapper, gradio('lora_menu'), gradio('model_status'), show_progress=False)
+
+ shared.gradio['download_model_button'].click(download_model_wrapper, gradio('custom_model_menu', 'download_specific_file'), gradio('model_status'), show_progress=True)
+ shared.gradio['get_file_list'].click(partial(download_model_wrapper, return_links=True), gradio('custom_model_menu', 'download_specific_file'), gradio('model_status'), show_progress=True)
+ shared.gradio['customized_template_submit'].click(save_instruction_template, gradio('model_menu', 'customized_template'), gradio('model_status'), show_progress=True)
+
+
+def load_model_wrapper(selected_model, loader, autoload=False):
+ try:
+ settings = get_model_metadata(selected_model)
+ except FileNotFoundError:
+ exc = traceback.format_exc()
+ yield exc.replace('\n', '\n\n')
+ return
+
+ if not autoload:
+ yield "### {}\n\n- Settings updated: Click \"Load\" to load the model\n- Max sequence length: {}".format(selected_model, settings['truncation_length_info'])
+ return
+
+ if selected_model == 'None':
+ yield "No model selected"
+ else:
+ try:
+ yield f"Loading `{selected_model}`..."
+ unload_model()
+ if selected_model != '':
+ shared.model, shared.tokenizer = load_model(selected_model, loader)
+
+ if shared.model is not None:
+ yield f"Successfully loaded `{selected_model}`."
+ else:
+ yield f"Failed to load `{selected_model}`."
+ except:
+ exc = traceback.format_exc()
+ logger.error('Failed to load the model.')
+ print(exc)
+ yield exc.replace('\n', '\n\n')
+
+
+def load_lora_wrapper(selected_loras):
+ yield ("Applying the following LoRAs to {}:\n\n{}".format(shared.model_name, '\n'.join(selected_loras)))
+ add_lora_to_model(selected_loras)
+ yield ("Successfuly applied the LoRAs")
+
+
+def download_model_wrapper(repo_id, specific_file, progress=gr.Progress(), return_links=False, check=False):
+ downloader_module = importlib.import_module("download-model")
+ downloader = downloader_module.ModelDownloader()
+ update_queue = queue.Queue()
+
+ try:
+ # Handle direct GGUF URLs
+ if repo_id.startswith("https://") and ("huggingface.co" in repo_id) and (repo_id.endswith(".gguf") or repo_id.endswith(".gguf?download=true")):
+ try:
+ path = repo_id.split("huggingface.co/")[1]
+ parts = path.split("/")
+ if len(parts) >= 2:
+ extracted_repo_id = f"{parts[0]}/{parts[1]}"
+ filename = repo_id.split("/")[-1].replace("?download=true", "")
+ repo_id = extracted_repo_id
+ specific_file = filename
+ except Exception as e:
+ yield f"Error parsing GGUF URL: {e}"
+ progress(0.0)
+ return
+
+ if not repo_id:
+ yield "Please enter a model path."
+ progress(0.0)
+ return
+
+ repo_id = repo_id.strip()
+ specific_file = specific_file.strip()
+
+ progress(0.0, "Preparing download...")
+
+ model, branch = downloader.sanitize_model_and_branch_names(repo_id, None)
+ yield "Getting download links from Hugging Face..."
+ links, sha256, is_lora, is_llamacpp, file_sizes = downloader.get_download_links_from_huggingface(model, branch, text_only=False, specific_file=specific_file)
+
+ if not links:
+ yield "No files found to download for the given model/criteria."
+ progress(0.0)
+ return
+
+ # Check for multiple GGUF files
+ gguf_files = [link for link in links if link.lower().endswith('.gguf')]
+ if len(gguf_files) > 1 and not specific_file:
+ # Sort by size in ascending order
+ gguf_data = []
+ for i, link in enumerate(links):
+ if link.lower().endswith('.gguf'):
+ file_size = file_sizes[i]
+ gguf_data.append((file_size, link))
+
+ gguf_data.sort(key=lambda x: x[0])
+
+ output = "Multiple GGUF files found. Please copy one of the following filenames to the 'File name' field above:\n\n```\n"
+ for file_size, link in gguf_data:
+ size_str = format_file_size(file_size)
+ output += f"{size_str} - {Path(link).name}\n"
+
+ output += "```"
+ yield output
+ return
+
+ if return_links:
+ # Sort by size in ascending order
+ file_data = list(zip(file_sizes, links))
+ file_data.sort(key=lambda x: x[0])
+
+ output = "```\n"
+ for file_size, link in file_data:
+ size_str = format_file_size(file_size)
+ output += f"{size_str} - {Path(link).name}\n"
+
+ output += "```"
+ yield output
+ return
+
+ yield "Determining output folder..."
+ output_folder = downloader.get_output_folder(
+ model, branch, is_lora, is_llamacpp=is_llamacpp,
+ model_dir=shared.args.model_dir if shared.args.model_dir != shared.args_defaults.model_dir else None
+ )
+
+ if output_folder == Path("user_data/models"):
+ output_folder = Path(shared.args.model_dir)
+ elif output_folder == Path("user_data/loras"):
+ output_folder = Path(shared.args.lora_dir)
+
+ if check:
+ yield "Checking previously downloaded files..."
+ progress(0.5, "Verifying files...")
+ downloader.check_model_files(model, branch, links, sha256, output_folder)
+ progress(1.0, "Verification complete.")
+ yield "File check complete."
+ return
+
+ yield ""
+ progress(0.0, "Download starting...")
+
+ def downloader_thread_target():
+ try:
+ downloader.download_model_files(
+ model, branch, links, sha256, output_folder,
+ progress_queue=update_queue,
+ threads=4,
+ is_llamacpp=is_llamacpp,
+ specific_file=specific_file
+ )
+ update_queue.put(("COMPLETED", f"Model successfully saved to `{output_folder}/`."))
+ except Exception as e:
+ tb_str = traceback.format_exc().replace('\n', '\n\n')
+ update_queue.put(("ERROR", tb_str))
+
+ download_thread = threading.Thread(target=downloader_thread_target)
+ download_thread.start()
+
+ while True:
+ try:
+ message = update_queue.get(timeout=0.2)
+ if not isinstance(message, tuple) or len(message) != 2:
+ continue
+
+ msg_identifier, data = message
+
+ if msg_identifier == "COMPLETED":
+ progress(1.0, "Download complete!")
+ yield data
+ break
+ elif msg_identifier == "ERROR":
+ progress(0.0, "Error occurred")
+ yield data
+ break
+ elif isinstance(msg_identifier, float):
+ progress_value = msg_identifier
+ description_str = data
+ progress(progress_value, f"Downloading: {description_str}")
+
+ except queue.Empty:
+ if not download_thread.is_alive():
+ yield "Download process finished."
+ break
+
+ download_thread.join()
+
+ except Exception as e:
+ progress(0.0)
+ tb_str = traceback.format_exc().replace('\n', '\n\n')
+ yield tb_str
+
+
+def update_truncation_length(current_length, state):
+ if 'loader' in state:
+ if state['loader'].lower().startswith('exllama') or state['loader'] == 'llama.cpp':
+ return state['ctx_size']
+
+ return current_length
+
+
+def get_initial_vram_info():
+ if shared.model_name != 'None' and shared.args.loader == 'llama.cpp':
+ return update_gpu_layers_and_vram(
+ shared.args.loader,
+ shared.model_name,
+ shared.args.gpu_layers,
+ shared.args.ctx_size,
+ shared.args.cache_type,
+ auto_adjust=False,
+ for_ui=True
+ )
+
+ return "
Estimated VRAM to load the model:
"
+
+
+def get_initial_gpu_layers_max():
+ if shared.model_name != 'None' and shared.args.loader == 'llama.cpp':
+ model_settings = get_model_metadata(shared.model_name)
+ return model_settings.get('max_gpu_layers', model_settings.get('gpu_layers', 256))
+
+ return 256
+
+
+def handle_load_model_event_initial(model, state):
+ state = apply_model_settings_to_state(model, state)
+ output = ui.apply_interface_values(state)
+ update_model_parameters(state) # This updates the command-line flags
+
+ vram_info = state.get('vram_info', "
Estimated VRAM to load the model:
")
+ return output + [state] + [vram_info]
+
+
+def handle_load_model_event_final(truncation_length, loader, state):
+ truncation_length = update_truncation_length(truncation_length, state)
+ return [truncation_length, loader]
+
+
+def handle_unload_model_click():
+ unload_model()
+ return "Model unloaded"
+
+
+def format_file_size(size_bytes):
+ """Convert bytes to human readable format with 2 decimal places for GB and above"""
+ if size_bytes == 0:
+ return "0 B"
+
+ size_names = ["B", "KB", "MB", "GB", "TB"]
+ i = int(math.floor(math.log(size_bytes, 1024)))
+ p = math.pow(1024, i)
+ s = size_bytes / p
+
+ if i >= 3: # GB or TB
+ return f"{s:.2f} {size_names[i]}"
+ else:
+ return f"{s:.1f} {size_names[i]}"
diff --git a/modules/ui_notebook.py b/modules/ui_notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fab879b8255ac1906252bd619911d75aba6ac77
--- /dev/null
+++ b/modules/ui_notebook.py
@@ -0,0 +1,287 @@
+import threading
+import time
+from pathlib import Path
+
+import gradio as gr
+
+from modules import logits, shared, ui, utils
+from modules.prompts import count_tokens, load_prompt
+from modules.text_generation import (
+ generate_reply_wrapper,
+ get_token_ids,
+ stop_everything_event
+)
+from modules.utils import gradio
+
+_notebook_file_lock = threading.Lock()
+_notebook_auto_save_timer = None
+_last_notebook_text = None
+_last_notebook_prompt = None
+
+inputs = ('textbox-notebook', 'interface_state')
+outputs = ('textbox-notebook', 'html-notebook')
+
+
+def create_ui():
+ mu = shared.args.multi_user
+ with gr.Row(visible=not shared.settings['show_two_notebook_columns']) as shared.gradio['notebook-tab']:
+ shared.gradio['last_input-notebook'] = gr.State('')
+ with gr.Row():
+ with gr.Column(scale=4):
+ with gr.Tab('Raw'):
+ with gr.Row():
+ shared.gradio['textbox-notebook'] = gr.Textbox(label="", value="", lines=27, elem_id='textbox-notebook', elem_classes=['textbox', 'add_scrollbar'])
+ shared.gradio['token-counter-notebook'] = gr.HTML(value="
0", elem_id="notebook-token-counter")
+
+ with gr.Tab('Markdown'):
+ shared.gradio['markdown_render-notebook'] = gr.Button('Render')
+ shared.gradio['markdown-notebook'] = gr.Markdown()
+
+ with gr.Tab('HTML'):
+ shared.gradio['html-notebook'] = gr.HTML()
+
+ with gr.Tab('Logits'):
+ with gr.Row():
+ with gr.Column(scale=10):
+ shared.gradio['get_logits-notebook'] = gr.Button('Get next token probabilities')
+ with gr.Column(scale=1):
+ shared.gradio['use_samplers-notebook'] = gr.Checkbox(label='Use samplers', value=True, elem_classes=['no-background'])
+
+ with gr.Row():
+ shared.gradio['logits-notebook'] = gr.Textbox(lines=23, label='Output', elem_classes=['textbox_logits_notebook', 'add_scrollbar'])
+ shared.gradio['logits-notebook-previous'] = gr.Textbox(lines=23, label='Previous output', elem_classes=['textbox_logits_notebook', 'add_scrollbar'])
+
+ with gr.Tab('Tokens'):
+ shared.gradio['get_tokens-notebook'] = gr.Button('Get token IDs for the input')
+ shared.gradio['tokens-notebook'] = gr.Textbox(lines=23, label='Tokens', elem_classes=['textbox_logits_notebook', 'add_scrollbar', 'monospace'])
+
+ with gr.Row():
+ shared.gradio['Undo'] = gr.Button('Undo', elem_classes='small-button')
+ shared.gradio['Regenerate-notebook'] = gr.Button('Regenerate', elem_classes='small-button')
+ shared.gradio['Stop-notebook'] = gr.Button('Stop', visible=False, elem_classes='small-button', elem_id='stop')
+ shared.gradio['Generate-notebook'] = gr.Button('Generate', variant='primary', elem_classes='small-button')
+
+ with gr.Column(scale=1):
+ gr.HTML('
')
+ with gr.Row():
+ shared.gradio['prompt_menu-notebook'] = gr.Dropdown(choices=utils.get_available_prompts(), value=shared.settings['prompt-notebook'], label='Prompt', elem_classes='slim-dropdown')
+
+ with gr.Row():
+ ui.create_refresh_button(shared.gradio['prompt_menu-notebook'], lambda: None, lambda: {'choices': utils.get_available_prompts()}, ['refresh-button'], interactive=not mu)
+ shared.gradio['new_prompt-notebook'] = gr.Button('New', elem_classes=['refresh-button'], interactive=not mu)
+ shared.gradio['rename_prompt-notebook'] = gr.Button('Rename', elem_classes=['refresh-button'], interactive=not mu)
+ shared.gradio['delete_prompt-notebook'] = gr.Button('🗑️', elem_classes=['refresh-button'], interactive=not mu)
+ shared.gradio['delete_prompt-confirm-notebook'] = gr.Button('Confirm', variant='stop', elem_classes=['refresh-button'], visible=False)
+ shared.gradio['delete_prompt-cancel-notebook'] = gr.Button('Cancel', elem_classes=['refresh-button'], visible=False)
+
+ with gr.Row(visible=False) as shared.gradio['rename-row-notebook']:
+ shared.gradio['rename_prompt_to-notebook'] = gr.Textbox(label="New name", elem_classes=['no-background'])
+ shared.gradio['rename_prompt-cancel-notebook'] = gr.Button('Cancel', elem_classes=['refresh-button'])
+ shared.gradio['rename_prompt-confirm-notebook'] = gr.Button('Confirm', elem_classes=['refresh-button'], variant='primary')
+
+
+def create_event_handlers():
+ shared.gradio['Generate-notebook'].click(
+ lambda x: x, gradio('textbox-notebook'), gradio('last_input-notebook')).then(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: [gr.update(visible=True), gr.update(visible=False)], None, gradio('Stop-notebook', 'Generate-notebook')).then(
+ generate_and_save_wrapper_notebook, gradio('textbox-notebook', 'interface_state', 'prompt_menu-notebook'), gradio(outputs), show_progress=False).then(
+ lambda state, text: state.update({'textbox-notebook': text}), gradio('interface_state', 'textbox-notebook'), None).then(
+ lambda: [gr.update(visible=False), gr.update(visible=True)], None, gradio('Stop-notebook', 'Generate-notebook')).then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['textbox-notebook'].submit(
+ lambda x: x, gradio('textbox-notebook'), gradio('last_input-notebook')).then(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: [gr.update(visible=True), gr.update(visible=False)], None, gradio('Stop-notebook', 'Generate-notebook')).then(
+ generate_and_save_wrapper_notebook, gradio('textbox-notebook', 'interface_state', 'prompt_menu-notebook'), gradio(outputs), show_progress=False).then(
+ lambda state, text: state.update({'textbox-notebook': text}), gradio('interface_state', 'textbox-notebook'), None).then(
+ lambda: [gr.update(visible=False), gr.update(visible=True)], None, gradio('Stop-notebook', 'Generate-notebook')).then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Regenerate-notebook'].click(
+ lambda x: x, gradio('last_input-notebook'), gradio('textbox-notebook'), show_progress=False).then(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ lambda: [gr.update(visible=True), gr.update(visible=False)], None, gradio('Stop-notebook', 'Generate-notebook')).then(
+ generate_and_save_wrapper_notebook, gradio('textbox-notebook', 'interface_state', 'prompt_menu-notebook'), gradio(outputs), show_progress=False).then(
+ lambda state, text: state.update({'textbox-notebook': text}), gradio('interface_state', 'textbox-notebook'), None).then(
+ lambda: [gr.update(visible=False), gr.update(visible=True)], None, gradio('Stop-notebook', 'Generate-notebook')).then(
+ None, None, None, js=f'() => {{{ui.audio_notification_js}}}')
+
+ shared.gradio['Undo'].click(
+ lambda x: x, gradio('last_input-notebook'), gradio('textbox-notebook'), show_progress=False).then(
+ lambda state, text: state.update({'textbox-notebook': text}), gradio('interface_state', 'textbox-notebook'), None)
+
+ shared.gradio['markdown_render-notebook'].click(lambda x: x, gradio('textbox-notebook'), gradio('markdown-notebook'), queue=False)
+ shared.gradio['Stop-notebook'].click(stop_everything_event, None, None, queue=False)
+ shared.gradio['prompt_menu-notebook'].change(load_prompt, gradio('prompt_menu-notebook'), gradio('textbox-notebook'), show_progress=False)
+ shared.gradio['new_prompt-notebook'].click(handle_new_prompt, None, gradio('prompt_menu-notebook'), show_progress=False)
+
+ shared.gradio['delete_prompt-notebook'].click(
+ lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)],
+ None,
+ gradio('delete_prompt-notebook', 'delete_prompt-cancel-notebook', 'delete_prompt-confirm-notebook'),
+ show_progress=False)
+
+ shared.gradio['delete_prompt-cancel-notebook'].click(
+ lambda: [gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)],
+ None,
+ gradio('delete_prompt-notebook', 'delete_prompt-cancel-notebook', 'delete_prompt-confirm-notebook'),
+ show_progress=False)
+
+ shared.gradio['delete_prompt-confirm-notebook'].click(
+ handle_delete_prompt_confirm_notebook,
+ gradio('prompt_menu-notebook'),
+ gradio('prompt_menu-notebook', 'delete_prompt-notebook', 'delete_prompt-cancel-notebook', 'delete_prompt-confirm-notebook'),
+ show_progress=False)
+
+ shared.gradio['rename_prompt-notebook'].click(
+ handle_rename_prompt_click_notebook,
+ gradio('prompt_menu-notebook'),
+ gradio('rename_prompt_to-notebook', 'rename_prompt-notebook', 'rename-row-notebook'),
+ show_progress=False)
+
+ shared.gradio['rename_prompt-cancel-notebook'].click(
+ lambda: [gr.update(visible=True), gr.update(visible=False)],
+ None,
+ gradio('rename_prompt-notebook', 'rename-row-notebook'),
+ show_progress=False)
+
+ shared.gradio['rename_prompt-confirm-notebook'].click(
+ handle_rename_prompt_confirm_notebook,
+ gradio('rename_prompt_to-notebook', 'prompt_menu-notebook'),
+ gradio('prompt_menu-notebook', 'rename_prompt-notebook', 'rename-row-notebook'),
+ show_progress=False)
+
+ shared.gradio['textbox-notebook'].input(lambda x: f"
{count_tokens(x)}", gradio('textbox-notebook'), gradio('token-counter-notebook'), show_progress=False)
+ shared.gradio['textbox-notebook'].change(
+ store_notebook_state_and_debounce,
+ gradio('textbox-notebook', 'prompt_menu-notebook'),
+ None,
+ show_progress=False
+ )
+
+ shared.gradio['get_logits-notebook'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ logits.get_next_logits, gradio('textbox-notebook', 'interface_state', 'use_samplers-notebook', 'logits-notebook'), gradio('logits-notebook', 'logits-notebook-previous'), show_progress=False)
+
+ shared.gradio['get_tokens-notebook'].click(get_token_ids, gradio('textbox-notebook'), gradio('tokens-notebook'), show_progress=False)
+
+
+def generate_and_save_wrapper_notebook(textbox_content, interface_state, prompt_name):
+ """Generate reply and automatically save the result for notebook mode with periodic saves"""
+ last_save_time = time.monotonic()
+ save_interval = 8
+ output = textbox_content
+
+ # Initial autosave
+ safe_autosave_prompt(output, prompt_name)
+
+ for i, (output, html_output) in enumerate(generate_reply_wrapper(textbox_content, interface_state)):
+ yield output, html_output
+
+ current_time = time.monotonic()
+ # Save on first iteration or if save_interval seconds have passed
+ if i == 0 or (current_time - last_save_time) >= save_interval:
+ safe_autosave_prompt(output, prompt_name)
+ last_save_time = current_time
+
+ # Final autosave
+ safe_autosave_prompt(output, prompt_name)
+
+
+def handle_new_prompt():
+ new_name = utils.current_time()
+
+ # Create the new prompt file
+ prompt_path = Path("user_data/logs/notebook") / f"{new_name}.txt"
+ prompt_path.parent.mkdir(parents=True, exist_ok=True)
+ prompt_path.write_text("In this story,", encoding='utf-8')
+
+ return gr.update(choices=utils.get_available_prompts(), value=new_name)
+
+
+def handle_delete_prompt_confirm_notebook(prompt_name):
+ available_prompts = utils.get_available_prompts()
+ current_index = available_prompts.index(prompt_name) if prompt_name in available_prompts else 0
+
+ (Path("user_data/logs/notebook") / f"{prompt_name}.txt").unlink(missing_ok=True)
+ available_prompts = utils.get_available_prompts()
+
+ if available_prompts:
+ new_value = available_prompts[min(current_index, len(available_prompts) - 1)]
+ else:
+ new_value = utils.current_time()
+ Path("user_data/logs/notebook").mkdir(parents=True, exist_ok=True)
+ (Path("user_data/logs/notebook") / f"{new_value}.txt").write_text("In this story,")
+ available_prompts = [new_value]
+
+ return [
+ gr.update(choices=available_prompts, value=new_value),
+ gr.update(visible=True),
+ gr.update(visible=False),
+ gr.update(visible=False)
+ ]
+
+
+def handle_rename_prompt_click_notebook(current_name):
+ return [
+ gr.update(value=current_name),
+ gr.update(visible=False),
+ gr.update(visible=True)
+ ]
+
+
+def handle_rename_prompt_confirm_notebook(new_name, current_name):
+ old_path = Path("user_data/logs/notebook") / f"{current_name}.txt"
+ new_path = Path("user_data/logs/notebook") / f"{new_name}.txt"
+
+ if old_path.exists() and not new_path.exists():
+ old_path.rename(new_path)
+
+ available_prompts = utils.get_available_prompts()
+ return [
+ gr.update(choices=available_prompts, value=new_name),
+ gr.update(visible=True),
+ gr.update(visible=False)
+ ]
+
+
+def autosave_prompt(text, prompt_name):
+ """Automatically save the text to the selected prompt file"""
+ if prompt_name and text.strip():
+ prompt_path = Path("user_data/logs/notebook") / f"{prompt_name}.txt"
+ prompt_path.parent.mkdir(parents=True, exist_ok=True)
+ prompt_path.write_text(text, encoding='utf-8')
+
+
+def safe_autosave_prompt(content, prompt_name):
+ """Thread-safe wrapper for autosave_prompt to prevent file corruption"""
+ with _notebook_file_lock:
+ autosave_prompt(content, prompt_name)
+
+
+def store_notebook_state_and_debounce(text, prompt_name):
+ """Store current notebook state and trigger debounced save"""
+ global _notebook_auto_save_timer, _last_notebook_text, _last_notebook_prompt
+
+ if shared.args.multi_user:
+ return
+
+ _last_notebook_text = text
+ _last_notebook_prompt = prompt_name
+
+ if _notebook_auto_save_timer is not None:
+ _notebook_auto_save_timer.cancel()
+
+ _notebook_auto_save_timer = threading.Timer(1.0, _perform_notebook_debounced_save)
+ _notebook_auto_save_timer.start()
+
+
+def _perform_notebook_debounced_save():
+ """Actually perform the notebook save using the stored state"""
+ try:
+ if _last_notebook_text is not None and _last_notebook_prompt is not None:
+ safe_autosave_prompt(_last_notebook_text, _last_notebook_prompt)
+ except Exception as e:
+ print(f"Notebook auto-save failed: {e}")
diff --git a/modules/ui_parameters.py b/modules/ui_parameters.py
new file mode 100644
index 0000000000000000000000000000000000000000..45bef5f9e3a17abb3b8ea70f7d807091525ee802
--- /dev/null
+++ b/modules/ui_parameters.py
@@ -0,0 +1,140 @@
+from pathlib import Path
+
+import gradio as gr
+
+from modules import loaders, presets, shared, ui, ui_chat, utils
+from modules.utils import gradio
+
+
+def create_ui():
+ mu = shared.args.multi_user
+ with gr.Tab("Parameters", elem_id="parameters"):
+ with gr.Tab("Generation"):
+ with gr.Row():
+ with gr.Column():
+ with gr.Row():
+ shared.gradio['preset_menu'] = gr.Dropdown(choices=utils.get_available_presets(), value=shared.settings['preset'], label='Preset', elem_classes='slim-dropdown')
+ ui.create_refresh_button(shared.gradio['preset_menu'], lambda: None, lambda: {'choices': utils.get_available_presets()}, 'refresh-button', interactive=not mu)
+ shared.gradio['save_preset'] = gr.Button('💾', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['delete_preset'] = gr.Button('🗑️', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['reset_preset'] = gr.Button('Restore preset', elem_classes='refresh-button', interactive=True)
+ shared.gradio['neutralize_samplers'] = gr.Button('Neutralize samplers', elem_classes='refresh-button', interactive=True)
+
+ with gr.Column():
+ shared.gradio['filter_by_loader'] = gr.Dropdown(label="Filter by loader", choices=["All"] + list(loaders.loaders_and_params.keys()) if not shared.args.portable else ['llama.cpp'], value="All", elem_classes='slim-dropdown')
+
+ with gr.Row():
+ with gr.Column():
+ with gr.Row():
+ with gr.Column():
+ gr.Markdown('## Curve shape')
+ shared.gradio['temperature'] = gr.Slider(0.01, 5, value=shared.settings['temperature'], step=0.01, label='temperature')
+ shared.gradio['dynatemp_low'] = gr.Slider(0.01, 5, value=shared.settings['dynatemp_low'], step=0.01, label='dynatemp_low', visible=shared.settings['dynamic_temperature'])
+ shared.gradio['dynatemp_high'] = gr.Slider(0.01, 5, value=shared.settings['dynatemp_high'], step=0.01, label='dynatemp_high', visible=shared.settings['dynamic_temperature'])
+ shared.gradio['dynatemp_exponent'] = gr.Slider(0.01, 5, value=shared.settings['dynatemp_exponent'], step=0.01, label='dynatemp_exponent', visible=shared.settings['dynamic_temperature'])
+ shared.gradio['smoothing_factor'] = gr.Slider(0.0, 10.0, value=shared.settings['smoothing_factor'], step=0.01, label='smoothing_factor', info='Activates Quadratic Sampling.')
+ shared.gradio['smoothing_curve'] = gr.Slider(1.0, 10.0, value=shared.settings['smoothing_curve'], step=0.01, label='smoothing_curve', info='Adjusts the dropoff curve of Quadratic Sampling.')
+ shared.gradio['dynamic_temperature'] = gr.Checkbox(value=shared.settings['dynamic_temperature'], label='dynamic_temperature')
+
+ gr.Markdown('## Curve cutoff')
+ shared.gradio['min_p'] = gr.Slider(0.0, 1.0, value=shared.settings['min_p'], step=0.01, label='min_p')
+ shared.gradio['top_n_sigma'] = gr.Slider(0.0, 5.0, value=shared.settings['top_n_sigma'], step=0.01, label='top_n_sigma')
+ shared.gradio['top_p'] = gr.Slider(0.0, 1.0, value=shared.settings['top_p'], step=0.01, label='top_p')
+ shared.gradio['top_k'] = gr.Slider(0, 200, value=shared.settings['top_k'], step=1, label='top_k')
+ shared.gradio['typical_p'] = gr.Slider(0.0, 1.0, value=shared.settings['typical_p'], step=0.01, label='typical_p')
+ shared.gradio['xtc_threshold'] = gr.Slider(0, 0.5, value=shared.settings['xtc_threshold'], step=0.01, label='xtc_threshold', info='If 2 or more tokens have probability above this threshold, consider removing all but the last one.')
+ shared.gradio['xtc_probability'] = gr.Slider(0, 1, value=shared.settings['xtc_probability'], step=0.01, label='xtc_probability', info='Probability that the removal will actually happen. 0 disables the sampler. 1 makes it always happen.')
+ shared.gradio['epsilon_cutoff'] = gr.Slider(0, 9, value=shared.settings['epsilon_cutoff'], step=0.01, label='epsilon_cutoff')
+ shared.gradio['eta_cutoff'] = gr.Slider(0, 20, value=shared.settings['eta_cutoff'], step=0.01, label='eta_cutoff')
+ shared.gradio['tfs'] = gr.Slider(0.0, 1.0, value=shared.settings['tfs'], step=0.01, label='tfs')
+ shared.gradio['top_a'] = gr.Slider(0.0, 1.0, value=shared.settings['top_a'], step=0.01, label='top_a')
+
+ gr.Markdown('## Repetition suppression')
+ shared.gradio['dry_multiplier'] = gr.Slider(0, 5, value=shared.settings['dry_multiplier'], step=0.01, label='dry_multiplier', info='Set to greater than 0 to enable DRY. Recommended value: 0.8.')
+ shared.gradio['dry_allowed_length'] = gr.Slider(1, 20, value=shared.settings['dry_allowed_length'], step=1, label='dry_allowed_length', info='Longest sequence that can be repeated without being penalized.')
+ shared.gradio['dry_base'] = gr.Slider(1, 4, value=shared.settings['dry_base'], step=0.01, label='dry_base', info='Controls how fast the penalty grows with increasing sequence length.')
+ shared.gradio['repetition_penalty'] = gr.Slider(1.0, 1.5, value=shared.settings['repetition_penalty'], step=0.01, label='repetition_penalty')
+ shared.gradio['frequency_penalty'] = gr.Slider(0, 2, value=shared.settings['frequency_penalty'], step=0.05, label='frequency_penalty')
+ shared.gradio['presence_penalty'] = gr.Slider(0, 2, value=shared.settings['presence_penalty'], step=0.05, label='presence_penalty')
+ shared.gradio['encoder_repetition_penalty'] = gr.Slider(0.8, 1.5, value=shared.settings['encoder_repetition_penalty'], step=0.01, label='encoder_repetition_penalty')
+ shared.gradio['no_repeat_ngram_size'] = gr.Slider(0, 20, step=1, value=shared.settings['no_repeat_ngram_size'], label='no_repeat_ngram_size')
+ shared.gradio['repetition_penalty_range'] = gr.Slider(0, 4096, step=64, value=shared.settings['repetition_penalty_range'], label='repetition_penalty_range')
+
+ with gr.Column():
+ gr.Markdown('## Alternative sampling methods')
+ shared.gradio['penalty_alpha'] = gr.Slider(0, 5, value=shared.settings['penalty_alpha'], label='penalty_alpha', info='For Contrastive Search. do_sample must be unchecked.')
+ shared.gradio['guidance_scale'] = gr.Slider(-0.5, 2.5, step=0.05, value=shared.settings['guidance_scale'], label='guidance_scale', info='For CFG. 1.5 is a good value.')
+ shared.gradio['mirostat_mode'] = gr.Slider(0, 2, step=1, value=shared.settings['mirostat_mode'], label='mirostat_mode', info='mode=1 is for llama.cpp only.')
+ shared.gradio['mirostat_tau'] = gr.Slider(0, 10, step=0.01, value=shared.settings['mirostat_tau'], label='mirostat_tau')
+ shared.gradio['mirostat_eta'] = gr.Slider(0, 1, step=0.01, value=shared.settings['mirostat_eta'], label='mirostat_eta')
+
+ gr.Markdown('## Other options')
+ shared.gradio['do_sample'] = gr.Checkbox(value=shared.settings['do_sample'], label='do_sample')
+ shared.gradio['temperature_last'] = gr.Checkbox(value=shared.settings['temperature_last'], label='temperature_last', info='Moves temperature/dynamic temperature/quadratic sampling to the end of the sampler stack, ignoring their positions in "Sampler priority".')
+ shared.gradio['sampler_priority'] = gr.Textbox(value=shared.settings['sampler_priority'], lines=10, label='Sampler priority', info='Parameter names separated by new lines or commas.', elem_classes=['add_scrollbar'])
+ shared.gradio['dry_sequence_breakers'] = gr.Textbox(value=shared.settings['dry_sequence_breakers'], label='dry_sequence_breakers', info='Tokens across which sequence matching is not continued. Specified as a comma-separated list of quoted strings.')
+
+ with gr.Column():
+ with gr.Row():
+ with gr.Column():
+ with gr.Blocks():
+ shared.gradio['max_new_tokens'] = gr.Slider(minimum=shared.settings['max_new_tokens_min'], maximum=shared.settings['max_new_tokens_max'], value=shared.settings['max_new_tokens'], step=1, label='max_new_tokens', info='⚠️ Setting this too high can cause prompt truncation.')
+ shared.gradio['prompt_lookup_num_tokens'] = gr.Slider(value=shared.settings['prompt_lookup_num_tokens'], minimum=0, maximum=10, step=1, label='prompt_lookup_num_tokens', info='Activates Prompt Lookup Decoding.')
+ shared.gradio['max_tokens_second'] = gr.Slider(value=shared.settings['max_tokens_second'], minimum=0, maximum=20, step=1, label='Maximum tokens/second', info='To make text readable in real time.')
+
+ shared.gradio['auto_max_new_tokens'] = gr.Checkbox(value=shared.settings['auto_max_new_tokens'], label='auto_max_new_tokens', info='Expand max_new_tokens to the available context length.')
+ shared.gradio['ban_eos_token'] = gr.Checkbox(value=shared.settings['ban_eos_token'], label='Ban the eos_token', info='Forces the model to never end the generation prematurely.')
+ shared.gradio['add_bos_token'] = gr.Checkbox(value=shared.settings['add_bos_token'], label='Add the bos_token to the beginning of prompts', info='Only applies to text completion (notebook). In chat mode, templates control BOS tokens.')
+ shared.gradio['skip_special_tokens'] = gr.Checkbox(value=shared.settings['skip_special_tokens'], label='Skip special tokens', info='Some specific models need this unset.')
+ shared.gradio['stream'] = gr.Checkbox(value=shared.settings['stream'], label='Activate text streaming')
+ shared.gradio['static_cache'] = gr.Checkbox(value=shared.settings['static_cache'], label='Static KV cache', info='Use a static cache for improved performance.')
+
+ with gr.Column():
+ shared.gradio['truncation_length'] = gr.Number(precision=0, step=256, value=get_truncation_length(), label='Truncate the prompt up to this length', info='The leftmost tokens are removed if the prompt exceeds this length.')
+ shared.gradio['seed'] = gr.Number(value=shared.settings['seed'], label='Seed (-1 for random)')
+ shared.gradio['custom_system_message'] = gr.Textbox(value=shared.settings['custom_system_message'], lines=2, label='Custom system message', info='If not empty, will be used instead of the default one.', elem_classes=['add_scrollbar'])
+ shared.gradio['custom_stopping_strings'] = gr.Textbox(lines=2, value=shared.settings["custom_stopping_strings"] or None, label='Custom stopping strings', info='Written between "" and separated by commas.', placeholder='"\\n", "\\nYou:"')
+ shared.gradio['custom_token_bans'] = gr.Textbox(value=shared.settings['custom_token_bans'] or None, label='Token bans', info='Token IDs to ban, separated by commas. The IDs can be found in the Default or Notebook tab.')
+ shared.gradio['negative_prompt'] = gr.Textbox(value=shared.settings['negative_prompt'], label='Negative prompt', info='For CFG. Only used when guidance_scale is different than 1.', lines=3, elem_classes=['add_scrollbar'])
+ with gr.Row() as shared.gradio['grammar_file_row']:
+ shared.gradio['grammar_file'] = gr.Dropdown(value='None', choices=utils.get_available_grammars(), label='Load grammar from file (.gbnf)', elem_classes='slim-dropdown')
+ ui.create_refresh_button(shared.gradio['grammar_file'], lambda: None, lambda: {'choices': utils.get_available_grammars()}, 'refresh-button', interactive=not mu)
+ shared.gradio['save_grammar'] = gr.Button('💾', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['delete_grammar'] = gr.Button('🗑️ ', elem_classes='refresh-button', interactive=not mu)
+
+ shared.gradio['grammar_string'] = gr.Textbox(value=shared.settings['grammar_string'], label='Grammar', lines=16, elem_classes=['add_scrollbar', 'monospace'])
+
+ ui_chat.create_chat_settings_ui()
+
+
+def create_event_handlers():
+ shared.gradio['filter_by_loader'].change(loaders.blacklist_samplers, gradio('filter_by_loader', 'dynamic_temperature'), gradio(loaders.list_all_samplers()), show_progress=False)
+ shared.gradio['preset_menu'].change(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ presets.load_preset_for_ui, gradio('preset_menu', 'interface_state'), gradio('interface_state') + gradio(presets.presets_params()), show_progress=False)
+
+ shared.gradio['reset_preset'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ presets.reset_preset_for_ui, gradio('preset_menu', 'interface_state'), gradio('interface_state') + gradio(presets.presets_params()), show_progress=False)
+
+ shared.gradio['neutralize_samplers'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ presets.neutralize_samplers_for_ui, gradio('interface_state'), gradio('interface_state') + gradio(presets.presets_params()), show_progress=False)
+
+ shared.gradio['grammar_file'].change(load_grammar, gradio('grammar_file'), gradio('grammar_string'), show_progress=False)
+ shared.gradio['dynamic_temperature'].change(lambda x: [gr.update(visible=x)] * 3, gradio('dynamic_temperature'), gradio('dynatemp_low', 'dynatemp_high', 'dynatemp_exponent'), show_progress=False)
+
+
+def get_truncation_length():
+ if 'ctx_size' in shared.provided_arguments or shared.args.ctx_size != shared.args_defaults.ctx_size:
+ return shared.args.ctx_size
+ else:
+ return shared.settings['truncation_length']
+
+
+def load_grammar(name):
+ p = Path(f'user_data/grammars/{name}')
+ if p.exists():
+ return open(p, 'r', encoding='utf-8').read()
+ else:
+ return ''
diff --git a/modules/ui_session.py b/modules/ui_session.py
new file mode 100644
index 0000000000000000000000000000000000000000..60b19f476cfa7e208eaf37093750a2a4b6f422df
--- /dev/null
+++ b/modules/ui_session.py
@@ -0,0 +1,110 @@
+import gradio as gr
+
+from modules import shared, ui, utils
+from modules.utils import gradio
+
+
+def create_ui():
+ mu = shared.args.multi_user
+ with gr.Tab("Session", elem_id="session-tab"):
+ with gr.Row():
+ with gr.Column():
+ gr.Markdown("## Settings")
+ shared.gradio['toggle_dark_mode'] = gr.Button('Toggle light/dark theme 💡', elem_classes='refresh-button')
+ shared.gradio['show_two_notebook_columns'] = gr.Checkbox(label='Show two columns in the Notebook tab', value=shared.settings['show_two_notebook_columns'])
+ shared.gradio['paste_to_attachment'] = gr.Checkbox(label='Turn long pasted text into attachments in the Chat tab', value=shared.settings['paste_to_attachment'], elem_id='paste_to_attachment')
+ shared.gradio['include_past_attachments'] = gr.Checkbox(label='Include attachments/search results from previous messages in the chat prompt', value=shared.settings['include_past_attachments'])
+
+ with gr.Column():
+ gr.Markdown("## Extensions & flags")
+ shared.gradio['save_settings'] = gr.Button('Save extensions settings to user_data/settings.yaml', elem_classes='refresh-button', interactive=not mu)
+ shared.gradio['reset_interface'] = gr.Button("Apply flags/extensions and restart", interactive=not mu)
+ with gr.Row():
+ with gr.Column():
+ shared.gradio['extensions_menu'] = gr.CheckboxGroup(choices=utils.get_available_extensions(), value=shared.args.extensions, label="Available extensions", info='Note that some of these extensions may require manually installing Python requirements through the command: pip install -r extensions/extension_name/requirements.txt', elem_classes='checkboxgroup-table')
+
+ with gr.Column():
+ shared.gradio['bool_menu'] = gr.CheckboxGroup(choices=get_boolean_arguments(), value=get_boolean_arguments(active=True), label="Boolean command-line flags", elem_classes='checkboxgroup-table')
+
+ shared.gradio['theme_state'] = gr.Textbox(visible=False, value='dark' if shared.settings['dark_theme'] else 'light')
+ if not mu:
+ shared.gradio['save_settings'].click(
+ ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then(
+ handle_save_settings, gradio('interface_state', 'preset_menu', 'extensions_menu', 'show_controls', 'theme_state'), gradio('save_contents', 'save_filename', 'save_root', 'file_saver'), show_progress=False)
+
+ shared.gradio['toggle_dark_mode'].click(
+ lambda x: 'dark' if x == 'light' else 'light', gradio('theme_state'), gradio('theme_state')).then(
+ None, None, None, js=f'() => {{{ui.dark_theme_js}; toggleDarkMode(); localStorage.setItem("theme", document.body.classList.contains("dark") ? "dark" : "light")}}')
+
+ shared.gradio['show_two_notebook_columns'].change(
+ handle_default_to_notebook_change,
+ gradio('show_two_notebook_columns', 'textbox-default', 'output_textbox', 'prompt_menu-default', 'textbox-notebook', 'prompt_menu-notebook'),
+ gradio('default-tab', 'notebook-tab', 'textbox-default', 'output_textbox', 'prompt_menu-default', 'textbox-notebook', 'prompt_menu-notebook')
+ )
+
+ # Reset interface event
+ if not mu:
+ shared.gradio['reset_interface'].click(
+ set_interface_arguments, gradio('extensions_menu', 'bool_menu'), None).then(
+ None, None, None, js='() => {document.body.innerHTML=\'
Reloading...
\'; setTimeout(function(){location.reload()},2500); return []}')
+
+
+def handle_save_settings(state, preset, extensions, show_controls, theme):
+ contents = ui.save_settings(state, preset, extensions, show_controls, theme, manual_save=True)
+ return [
+ contents,
+ "settings.yaml",
+ "user_data/",
+ gr.update(visible=True)
+ ]
+
+
+def handle_default_to_notebook_change(show_two_columns, default_input, default_output, default_prompt, notebook_input, notebook_prompt):
+ if show_two_columns:
+ # Notebook to default
+ return [
+ gr.update(visible=True),
+ gr.update(visible=False),
+ notebook_input,
+ "",
+ gr.update(value=notebook_prompt, choices=utils.get_available_prompts()),
+ gr.update(),
+ gr.update(),
+ ]
+ else:
+ # Default to notebook
+ return [
+ gr.update(visible=False),
+ gr.update(visible=True),
+ gr.update(),
+ gr.update(),
+ gr.update(),
+ default_input,
+ gr.update(value=default_prompt, choices=utils.get_available_prompts())
+ ]
+
+
+def set_interface_arguments(extensions, bool_active):
+ shared.args.extensions = extensions
+
+ bool_list = get_boolean_arguments()
+
+ for k in bool_list:
+ setattr(shared.args, k, False)
+ for k in bool_active:
+ setattr(shared.args, k, True)
+ if k == 'api':
+ shared.add_extension('openai', last=True)
+
+ shared.need_restart = True
+
+
+def get_boolean_arguments(active=False):
+ cmd_list = vars(shared.args)
+ bool_list = sorted([k for k in cmd_list if type(cmd_list[k]) is bool and k not in ui.list_model_elements()])
+ bool_active = [k for k in bool_list if vars(shared.args)[k]]
+
+ if active:
+ return bool_active
+ else:
+ return bool_list
diff --git a/modules/utils.py b/modules/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8d23a0284ce2776b229b711e588d8466a6c201d
--- /dev/null
+++ b/modules/utils.py
@@ -0,0 +1,243 @@
+import os
+import re
+from datetime import datetime
+from pathlib import Path
+
+from modules import shared
+from modules.logging_colors import logger
+
+
+# Helper function to get multiple values from shared.gradio
+def gradio(*keys):
+ if len(keys) == 1 and type(keys[0]) in [list, tuple]:
+ keys = keys[0]
+
+ return [shared.gradio[k] for k in keys]
+
+
+def save_file(fname, contents):
+ if fname == '':
+ logger.error('File name is empty!')
+ return
+
+ root_folder = Path(__file__).resolve().parent.parent
+ abs_path_str = os.path.abspath(fname)
+ rel_path_str = os.path.relpath(abs_path_str, root_folder)
+ rel_path = Path(rel_path_str)
+ if rel_path.parts[0] == '..':
+ logger.error(f'Invalid file path: \"{fname}\"')
+ return
+
+ with open(abs_path_str, 'w', encoding='utf-8') as f:
+ f.write(contents)
+
+ logger.info(f'Saved \"{abs_path_str}\".')
+
+
+def delete_file(fname):
+ if fname == '':
+ logger.error('File name is empty!')
+ return
+
+ root_folder = Path(__file__).resolve().parent.parent
+ abs_path_str = os.path.abspath(fname)
+ rel_path_str = os.path.relpath(abs_path_str, root_folder)
+ rel_path = Path(rel_path_str)
+ if rel_path.parts[0] == '..':
+ logger.error(f'Invalid file path: \"{fname}\"')
+ return
+
+ if rel_path.exists():
+ rel_path.unlink()
+ logger.info(f'Deleted \"{fname}\".')
+
+
+def current_time():
+ return f"{datetime.now().strftime('%Y-%m-%d_%Hh%Mm%Ss')}"
+
+
+def atoi(text):
+ return int(text) if text.isdigit() else text.lower()
+
+
+# Replace multiple string pairs in a string
+def replace_all(text, dic):
+ for i, j in dic.items():
+ text = text.replace(i, j)
+
+ return text
+
+
+def natural_keys(text):
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
+
+
+def check_model_loaded():
+ if shared.model_name == 'None' or shared.model is None:
+ if len(get_available_models()) == 0:
+ error_msg = "No model is loaded.\n\nTo get started:\n1) Place a GGUF file in your user_data/models folder\n2) Go to the Model tab and select it"
+ logger.error(error_msg)
+ return False, error_msg
+ else:
+ error_msg = "No model is loaded. Please select one in the Model tab."
+ logger.error(error_msg)
+ return False, error_msg
+
+ return True, None
+
+
+def resolve_model_path(model_name_or_path):
+ """
+ Resolves a model path, checking for a direct path
+ before the default models directory.
+ """
+
+ path_candidate = Path(model_name_or_path)
+ if path_candidate.exists():
+ return path_candidate
+ else:
+ return Path(f'{shared.args.model_dir}/{model_name_or_path}')
+
+
+def get_available_models():
+ # Get all GGUF files
+ gguf_files = get_available_ggufs()
+
+ # Filter out non-first parts of multipart GGUF files
+ filtered_gguf_files = []
+ for gguf_path in gguf_files:
+ filename = os.path.basename(gguf_path)
+
+ match = re.search(r'-(\d+)-of-\d+\.gguf$', filename)
+
+ if match:
+ part_number = match.group(1)
+ # Keep only if it's part 1
+ if part_number.lstrip("0") == "1":
+ filtered_gguf_files.append(gguf_path)
+ else:
+ # Not a multi-part file
+ filtered_gguf_files.append(gguf_path)
+
+ model_dir = Path(shared.args.model_dir)
+
+ # Find top-level directories containing GGUF files
+ dirs_with_gguf = set()
+ for gguf_path in gguf_files:
+ path = Path(gguf_path)
+ if len(path.parts) > 0:
+ dirs_with_gguf.add(path.parts[0])
+
+ # Find directories with safetensors files
+ dirs_with_safetensors = set()
+ for item in os.listdir(model_dir):
+ item_path = model_dir / item
+ if item_path.is_dir():
+ if any(file.lower().endswith(('.safetensors', '.pt')) for file in os.listdir(item_path) if (item_path / file).is_file()):
+ dirs_with_safetensors.add(item)
+
+ # Find valid model directories
+ model_dirs = []
+ for item in os.listdir(model_dir):
+ item_path = model_dir / item
+ if not item_path.is_dir():
+ continue
+
+ # Include directory if it either doesn't contain GGUF files
+ # or contains both GGUF and safetensors files
+ if item not in dirs_with_gguf or item in dirs_with_safetensors:
+ model_dirs.append(item)
+
+ model_dirs = sorted(model_dirs, key=natural_keys)
+
+ return filtered_gguf_files + model_dirs
+
+
+def get_available_ggufs():
+ model_list = []
+ model_dir = Path(shared.args.model_dir)
+
+ for dirpath, _, files in os.walk(model_dir, followlinks=True):
+ for file in files:
+ if file.lower().endswith(".gguf"):
+ model_path = Path(dirpath) / file
+ rel_path = model_path.relative_to(model_dir)
+ model_list.append(str(rel_path))
+
+ return sorted(model_list, key=natural_keys)
+
+
+def get_available_mmproj():
+ mmproj_dir = Path('user_data/mmproj')
+ if not mmproj_dir.exists():
+ return ['None']
+
+ mmproj_files = []
+ for item in mmproj_dir.iterdir():
+ if item.is_file() and item.suffix.lower() in ('.gguf', '.bin'):
+ mmproj_files.append(item.name)
+
+ return ['None'] + sorted(mmproj_files, key=natural_keys)
+
+
+def get_available_presets():
+ return sorted(set((k.stem for k in Path('user_data/presets').glob('*.yaml'))), key=natural_keys)
+
+
+def get_available_prompts():
+ notebook_dir = Path('user_data/logs/notebook')
+ notebook_dir.mkdir(parents=True, exist_ok=True)
+
+ prompt_files = list(notebook_dir.glob('*.txt'))
+ sorted_files = sorted(prompt_files, key=lambda x: x.stat().st_mtime, reverse=True)
+ prompts = [file.stem for file in sorted_files]
+ return prompts
+
+
+def get_available_characters():
+ paths = (x for x in Path('user_data/characters').iterdir() if x.suffix in ('.json', '.yaml', '.yml'))
+ return sorted(set((k.stem for k in paths)), key=natural_keys)
+
+
+def get_available_instruction_templates():
+ path = "user_data/instruction-templates"
+ paths = []
+ if os.path.exists(path):
+ paths = (x for x in Path(path).iterdir() if x.suffix in ('.json', '.yaml', '.yml'))
+
+ return ['None'] + sorted(set((k.stem for k in paths)), key=natural_keys)
+
+
+def get_available_extensions():
+ # User extensions (higher priority)
+ user_extensions = []
+ user_ext_path = Path('user_data/extensions')
+ if user_ext_path.exists():
+ user_exts = map(lambda x: x.parts[2], user_ext_path.glob('*/script.py'))
+ user_extensions = sorted(set(user_exts), key=natural_keys)
+
+ # System extensions (excluding those overridden by user extensions)
+ system_exts = map(lambda x: x.parts[1], Path('extensions').glob('*/script.py'))
+ system_extensions = sorted(set(system_exts) - set(user_extensions), key=natural_keys)
+
+ return user_extensions + system_extensions
+
+
+def get_available_loras():
+ return ['None'] + sorted([item.name for item in list(Path(shared.args.lora_dir).glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=natural_keys)
+
+
+def get_datasets(path: str, ext: str):
+ # include subdirectories for raw txt files to allow training from a subdirectory of txt files
+ if ext == "txt":
+ return ['None'] + sorted(set([k.stem for k in list(Path(path).glob('*.txt')) + list(Path(path).glob('*/')) if k.stem != 'put-trainer-datasets-here']), key=natural_keys)
+
+ return ['None'] + sorted(set([k.stem for k in Path(path).glob(f'*.{ext}') if k.stem != 'put-trainer-datasets-here']), key=natural_keys)
+
+
+def get_available_chat_styles():
+ return sorted(set(('-'.join(k.stem.split('-')[1:]) for k in Path('css').glob('chat_style*.css'))), key=natural_keys)
+
+
+def get_available_grammars():
+ return ['None'] + sorted([item.name for item in list(Path('user_data/grammars').glob('*.gbnf'))], key=natural_keys)
diff --git a/modules/web_search.py b/modules/web_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..597af4b289e638345059ca3c81e34c9c1de5244f
--- /dev/null
+++ b/modules/web_search.py
@@ -0,0 +1,172 @@
+import concurrent.futures
+import html
+import random
+import re
+import urllib.request
+from concurrent.futures import as_completed
+from datetime import datetime
+from urllib.parse import quote_plus
+
+import requests
+
+from modules import shared
+from modules.logging_colors import logger
+
+
+def get_current_timestamp():
+ """Returns the current time in 24-hour format"""
+ return datetime.now().strftime('%b %d, %Y %H:%M')
+
+
+def download_web_page(url, timeout=10):
+ """
+ Download a web page and convert its HTML content to structured Markdown text.
+ """
+ import html2text
+
+ try:
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
+ }
+ response = requests.get(url, headers=headers, timeout=timeout)
+ response.raise_for_status() # Raise an exception for bad status codes
+
+ # Initialize the HTML to Markdown converter
+ h = html2text.HTML2Text()
+ h.body_width = 0
+ h.ignore_images = True
+ h.ignore_links = True
+
+ # Convert the HTML to Markdown
+ markdown_text = h.handle(response.text)
+
+ return markdown_text
+ except requests.exceptions.RequestException as e:
+ logger.error(f"Error downloading {url}: {e}")
+ return ""
+ except Exception as e:
+ logger.error(f"An unexpected error occurred: {e}")
+ return ""
+
+
+def perform_web_search(query, num_pages=3, max_workers=5, timeout=10):
+ """Perform web search and return results with content"""
+ try:
+ search_url = f"https://html.duckduckgo.com/html/?q={quote_plus(query)}"
+
+ agents = [
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
+ ]
+
+ response_text = ""
+ req = urllib.request.Request(search_url, headers={'User-Agent': random.choice(agents)})
+ with urllib.request.urlopen(req, timeout=timeout) as response:
+ response_text = response.read().decode('utf-8')
+
+ # Extract results with regex
+ titles = re.findall(r'
]*class="[^"]*result__a[^"]*"[^>]*>(.*?)', response_text, re.DOTALL)
+ urls = re.findall(r'
]*class="[^"]*result__url[^"]*"[^>]*>(.*?)', response_text, re.DOTALL)
+
+ # Prepare download tasks
+ download_tasks = []
+ for i in range(min(len(titles), len(urls), num_pages)):
+ url = f"https://{urls[i].strip()}"
+ title = re.sub(r'<[^>]+>', '', titles[i]).strip()
+ title = html.unescape(title)
+ download_tasks.append((url, title, i))
+
+ search_results = [None] * len(download_tasks) # Pre-allocate to maintain order
+
+ # Download pages in parallel
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
+ # Submit all download tasks
+ future_to_task = {
+ executor.submit(download_web_page, task[0]): task
+ for task in download_tasks
+ }
+
+ # Collect results as they complete
+ for future in as_completed(future_to_task):
+ url, title, index = future_to_task[future]
+ try:
+ content = future.result()
+ search_results[index] = {
+ 'title': title,
+ 'url': url,
+ 'content': content
+ }
+ except Exception:
+ search_results[index] = {
+ 'title': title,
+ 'url': url,
+ 'content': ''
+ }
+
+ return search_results
+
+ except Exception as e:
+ logger.error(f"Error performing web search: {e}")
+ return []
+
+
+def truncate_content_by_tokens(content, max_tokens=8192):
+ """Truncate content to fit within token limit using binary search"""
+ if len(shared.tokenizer.encode(content)) <= max_tokens:
+ return content
+
+ left, right = 0, len(content)
+ while left < right:
+ mid = (left + right + 1) // 2
+ if len(shared.tokenizer.encode(content[:mid])) <= max_tokens:
+ left = mid
+ else:
+ right = mid - 1
+
+ return content[:left]
+
+
+def add_web_search_attachments(history, row_idx, user_message, search_query, state):
+ """Perform web search and add results as attachments"""
+ if not search_query:
+ logger.warning("No search query provided")
+ return
+
+ try:
+ logger.info(f"Using search query: {search_query}")
+
+ # Perform web search
+ num_pages = int(state.get('web_search_pages', 3))
+ search_results = perform_web_search(search_query, num_pages)
+
+ if not search_results:
+ logger.warning("No search results found")
+ return
+
+ # Filter out failed downloads before adding attachments
+ successful_results = [result for result in search_results if result['content'].strip()]
+
+ if not successful_results:
+ logger.warning("No successful downloads to add as attachments")
+ return
+
+ # Add search results as attachments
+ key = f"user_{row_idx}"
+ if key not in history['metadata']:
+ history['metadata'][key] = {"timestamp": get_current_timestamp()}
+ if "attachments" not in history['metadata'][key]:
+ history['metadata'][key]["attachments"] = []
+
+ for result in successful_results:
+ attachment = {
+ "name": result['title'],
+ "type": "text/html",
+ "url": result['url'],
+ "content": truncate_content_by_tokens(result['content'])
+ }
+ history['metadata'][key]["attachments"].append(attachment)
+
+ logger.info(f"Added {len(successful_results)} successful web search results as attachments.")
+
+ except Exception as e:
+ logger.error(f"Error in web search: {e}")
diff --git a/one_click.py b/one_click.py
new file mode 100644
index 0000000000000000000000000000000000000000..881d7489b9e595be8354f6a4f16cc87b83258e5b
--- /dev/null
+++ b/one_click.py
@@ -0,0 +1,550 @@
+import argparse
+import glob
+import hashlib
+import json
+import os
+import platform
+import re
+import signal
+import site
+import subprocess
+import sys
+
+# Remove the '# ' from the following lines as needed for your AMD GPU on Linux
+# os.environ["ROCM_PATH"] = '/opt/rocm'
+# os.environ["HSA_OVERRIDE_GFX_VERSION"] = '10.3.0'
+# os.environ["HCC_AMDGPU_TARGET"] = 'gfx1030'
+
+# Define the required versions
+TORCH_VERSION = "2.7.1"
+PYTHON_VERSION = "3.11"
+LIBSTDCXX_VERSION_LINUX = "12.1.0"
+
+# Environment
+script_dir = os.getcwd()
+conda_env_path = os.path.join(script_dir, "installer_files", "env")
+state_file = '.installer_state.json'
+
+# Command-line flags
+flags = f"{' '.join([flag for flag in sys.argv[1:] if flag != '--update-wizard'])}"
+
+
+def signal_handler(sig, frame):
+ sys.exit(0)
+
+
+signal.signal(signal.SIGINT, signal_handler)
+
+
+def is_linux():
+ return sys.platform.startswith("linux")
+
+
+def is_windows():
+ return sys.platform.startswith("win")
+
+
+def is_macos():
+ return sys.platform.startswith("darwin")
+
+
+def is_x86_64():
+ return platform.machine() == "x86_64"
+
+
+def is_installed():
+ site_packages_path = None
+ for sitedir in site.getsitepackages():
+ if "site-packages" in sitedir and conda_env_path in sitedir:
+ site_packages_path = sitedir
+ break
+
+ if site_packages_path:
+ return os.path.isfile(os.path.join(site_packages_path, 'torch', '__init__.py'))
+ else:
+ return os.path.isdir(conda_env_path)
+
+
+def cpu_has_avx2():
+ try:
+ import cpuinfo
+ info = cpuinfo.get_cpu_info()
+ return 'avx2' in info['flags']
+ except:
+ return True
+
+
+def cpu_has_amx():
+ try:
+ import cpuinfo
+ info = cpuinfo.get_cpu_info()
+ return 'amx' in info['flags']
+ except:
+ return True
+
+
+def load_state():
+ """Load installer state from JSON file"""
+ if os.path.exists(state_file):
+ try:
+ with open(state_file, 'r') as f:
+ return json.load(f)
+ except:
+ return {}
+ return {}
+
+
+def save_state(state):
+ """Save installer state to JSON file"""
+ with open(state_file, 'w') as f:
+ json.dump(state, f)
+
+
+def get_gpu_choice():
+ """Get GPU choice from state file or ask user"""
+ state = load_state()
+ gpu_choice = state.get('gpu_choice')
+
+ if not gpu_choice:
+ if "GPU_CHOICE" in os.environ:
+ choice = os.environ["GPU_CHOICE"].upper()
+ print_big_message(f"Selected GPU choice \"{choice}\" based on the GPU_CHOICE environment variable.")
+ else:
+ choice = get_user_choice(
+ "What is your GPU?",
+ {
+ 'A': 'NVIDIA',
+ 'B': 'AMD - Linux/macOS only, requires ROCm 6.2.4',
+ 'C': 'Apple M Series',
+ 'D': 'Intel Arc (beta)',
+ 'N': 'CPU mode'
+ },
+ )
+
+ # Convert choice to GPU name
+ gpu_choice = {"A": "NVIDIA_CUDA128", "B": "AMD", "C": "APPLE", "D": "INTEL", "N": "NONE"}[choice]
+
+ # Save choice to state
+ state['gpu_choice'] = gpu_choice
+ save_state(state)
+
+ return gpu_choice
+
+
+def get_pytorch_install_command(gpu_choice):
+ """Get PyTorch installation command based on GPU choice"""
+ base_cmd = f"python -m pip install torch=={TORCH_VERSION} "
+
+ if gpu_choice == "NVIDIA_CUDA128":
+ return base_cmd + "--index-url https://download.pytorch.org/whl/cu128"
+ elif gpu_choice == "AMD":
+ return base_cmd + "--index-url https://download.pytorch.org/whl/rocm6.2.4"
+ elif gpu_choice in ["APPLE", "NONE"]:
+ return base_cmd + "--index-url https://download.pytorch.org/whl/cpu"
+ elif gpu_choice == "INTEL":
+ if is_linux():
+ return "python -m pip install torch==2.1.0a0 intel-extension-for-pytorch==2.1.10+xpu --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/"
+ else:
+ return "python -m pip install torch==2.1.0a0 intel-extension-for-pytorch==2.1.10 --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/"
+ else:
+ return base_cmd
+
+
+def get_pytorch_update_command(gpu_choice):
+ """Get PyTorch update command based on GPU choice"""
+ base_cmd = f"python -m pip install --upgrade torch=={TORCH_VERSION} "
+
+ if gpu_choice == "NVIDIA_CUDA128":
+ return f"{base_cmd} --index-url https://download.pytorch.org/whl/cu128"
+ elif gpu_choice == "AMD":
+ return f"{base_cmd} --index-url https://download.pytorch.org/whl/rocm6.2.4"
+ elif gpu_choice in ["APPLE", "NONE"]:
+ return f"{base_cmd} --index-url https://download.pytorch.org/whl/cpu"
+ elif gpu_choice == "INTEL":
+ intel_extension = "intel-extension-for-pytorch==2.1.10+xpu" if is_linux() else "intel-extension-for-pytorch==2.1.10"
+ return f"{base_cmd} {intel_extension} --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/"
+ else:
+ return base_cmd
+
+
+def get_requirements_file(gpu_choice):
+ """Get requirements file path based on GPU choice"""
+ requirements_base = os.path.join("requirements", "full")
+
+ if gpu_choice == "NVIDIA_CUDA128":
+ file_name = f"requirements{'_noavx2' if not cpu_has_avx2() else ''}.txt"
+ elif gpu_choice == "AMD":
+ file_name = f"requirements_amd{'_noavx2' if not cpu_has_avx2() else ''}.txt"
+ elif gpu_choice == "APPLE":
+ file_name = f"requirements_apple_{'intel' if is_x86_64() else 'silicon'}.txt"
+ elif gpu_choice in ["INTEL", "NONE"]:
+ file_name = f"requirements_cpu_only{'_noavx2' if not cpu_has_avx2() else ''}.txt"
+ else:
+ raise ValueError(f"Unknown GPU choice: {gpu_choice}")
+
+ return os.path.join(requirements_base, file_name)
+
+
+def get_current_commit():
+ result = run_cmd("git rev-parse HEAD", capture_output=True, environment=True)
+ return result.stdout.decode('utf-8').strip()
+
+
+def get_extensions_names():
+ return [foldername for foldername in os.listdir('extensions') if os.path.isfile(os.path.join('extensions', foldername, 'requirements.txt'))]
+
+
+def check_env():
+ # If we have access to conda, we are probably in an environment
+ conda_exist = run_cmd("conda", environment=True, capture_output=True).returncode == 0
+ if not conda_exist:
+ print("Conda is not installed. Exiting...")
+ sys.exit(1)
+
+ # Ensure this is a new environment and not the base environment
+ if os.environ.get("CONDA_DEFAULT_ENV", "") == "base":
+ print("Create an environment for this project and activate it. Exiting...")
+ sys.exit(1)
+
+
+def clear_cache():
+ run_cmd("conda clean -a -y", environment=True)
+ run_cmd("python -m pip cache purge", environment=True)
+
+
+def run_cmd(cmd, assert_success=False, environment=False, capture_output=False, env=None):
+ # Use the conda environment
+ if environment:
+ if is_windows():
+ conda_bat_path = os.path.join(script_dir, "installer_files", "conda", "condabin", "conda.bat")
+ cmd = f'"{conda_bat_path}" activate "{conda_env_path}" >nul && {cmd}'
+ else:
+ conda_sh_path = os.path.join(script_dir, "installer_files", "conda", "etc", "profile.d", "conda.sh")
+ cmd = f'. "{conda_sh_path}" && conda activate "{conda_env_path}" && {cmd}'
+
+ # Set executable to None for Windows, bash for everything else
+ executable = None if is_windows() else 'bash'
+
+ # Run shell commands
+ result = subprocess.run(cmd, shell=True, capture_output=capture_output, env=env, executable=executable)
+
+ # Assert the command ran successfully
+ if assert_success and result.returncode != 0:
+ print(f"Command '{cmd}' failed with exit status code '{str(result.returncode)}'.\n\nExiting now.\nTry running the start/update script again.")
+ sys.exit(1)
+
+ return result
+
+
+def print_big_message(message):
+ message = message.strip()
+ lines = message.split('\n')
+ print("\n\n*******************************************************************")
+ for line in lines:
+ print("*", line)
+
+ print("*******************************************************************\n\n")
+
+
+def calculate_file_hash(file_path):
+ p = os.path.join(script_dir, file_path)
+ if os.path.isfile(p):
+ with open(p, 'rb') as f:
+ return hashlib.sha256(f.read()).hexdigest()
+ else:
+ return ''
+
+
+def generate_alphabetic_sequence(index):
+ result = ''
+ while index >= 0:
+ index, remainder = divmod(index, 26)
+ result = chr(ord('A') + remainder) + result
+ index -= 1
+
+ return result
+
+
+def get_user_choice(question, options_dict):
+ print()
+ print(question)
+ print()
+
+ for key, value in options_dict.items():
+ print(f"{key}) {value}")
+
+ print()
+
+ choice = input("Input> ").upper()
+ while choice not in options_dict.keys():
+ print("Invalid choice. Please try again.")
+ choice = input("Input> ").upper()
+
+ return choice
+
+
+def update_pytorch_and_python():
+ print_big_message("Checking for PyTorch updates.")
+ gpu_choice = get_gpu_choice()
+ install_cmd = get_pytorch_update_command(gpu_choice)
+ run_cmd(install_cmd, assert_success=True, environment=True)
+
+
+def clean_outdated_pytorch_cuda_dependencies():
+ patterns = ["cu121", "cu122", "torch2.4", "torchvision", "torchaudio"]
+ result = run_cmd("python -m pip list --format=freeze", capture_output=True, environment=True)
+ matching_packages = []
+
+ for line in result.stdout.decode('utf-8').splitlines():
+ if "==" in line:
+ pkg_name, version = line.split('==', 1)
+ if any(pattern in version for pattern in patterns):
+ matching_packages.append(pkg_name)
+
+ if matching_packages:
+ print(f"\nUninstalling: {', '.join(matching_packages)}\n")
+ run_cmd(f"python -m pip uninstall -y {' '.join(matching_packages)}", assert_success=True, environment=True)
+
+ return matching_packages
+
+
+def install_webui():
+ if os.path.isfile(state_file):
+ os.remove(state_file)
+
+ # Get GPU choice and save it to state
+ gpu_choice = get_gpu_choice()
+
+ # Write a flag to CMD_FLAGS.txt for CPU mode
+ if gpu_choice == "NONE":
+ cmd_flags_path = os.path.join(script_dir, "user_data", "CMD_FLAGS.txt")
+ with open(cmd_flags_path, 'r+') as cmd_flags_file:
+ if "--cpu" not in cmd_flags_file.read():
+ print_big_message("Adding the --cpu flag to user_data/CMD_FLAGS.txt.")
+ cmd_flags_file.write("\n--cpu\n")
+
+ # Handle CUDA version display
+ elif any((is_windows(), is_linux())) and gpu_choice == "NVIDIA_CUDA128":
+ print("CUDA: 12.8")
+
+ # No PyTorch for AMD on Windows (?)
+ elif is_windows() and gpu_choice == "AMD":
+ print("PyTorch setup on Windows is not implemented yet. Exiting...")
+ sys.exit(1)
+
+ # Install Git and then Pytorch
+ print_big_message("Installing PyTorch.")
+ install_pytorch = get_pytorch_install_command(gpu_choice)
+ run_cmd(f"conda install -y ninja git && {install_pytorch} && python -m pip install py-cpuinfo==9.0.0", assert_success=True, environment=True)
+
+ if gpu_choice == "INTEL":
+ # Install oneAPI dependencies via conda
+ print_big_message("Installing Intel oneAPI runtime libraries.")
+ run_cmd("conda install -y -c https://software.repos.intel.com/python/conda/ -c conda-forge dpcpp-cpp-rt=2024.0 mkl-dpcpp=2024.0", environment=True)
+ # Install libuv required by Intel-patched torch
+ run_cmd("conda install -y libuv", environment=True)
+
+ # Install the webui requirements
+ update_requirements(initial_installation=True, pull=False)
+
+
+def update_requirements(initial_installation=False, pull=True):
+ # Create .git directory if missing
+ if not os.path.exists(os.path.join(script_dir, ".git")):
+ run_cmd(
+ "git init -b main && git remote add origin https://github.com/oobabooga/text-generation-webui && "
+ "git fetch && git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main && "
+ "git reset --hard origin/main && git branch --set-upstream-to=origin/main",
+ environment=True,
+ assert_success=True
+ )
+
+ # Check for outdated CUDA 12.4 installs and refuse to update
+ state = load_state()
+ if state.get('gpu_choice') == 'NVIDIA':
+ print_big_message(
+ "Your current installation uses CUDA 12.4, which has been removed.\n"
+ "To update to the new default (CUDA 12.8), a clean installation is required.\n\n"
+ "INSTRUCTIONS:\n"
+ "1. Delete the 'installer_files' folder in your text-generation-webui directory.\n"
+ "2. Run the start script again (e.g., start_windows.bat).\n\n"
+ "This will create a fresh environment with the latest software."
+ )
+ sys.exit(0)
+
+ current_commit = get_current_commit()
+ wheels_changed = not os.path.exists(state_file)
+ if not wheels_changed:
+ state = load_state()
+ if 'wheels_changed' in state or state.get('last_installed_commit') != current_commit:
+ wheels_changed = True
+
+ gpu_choice = get_gpu_choice()
+ requirements_file = get_requirements_file(gpu_choice)
+
+ if pull:
+ # Read .whl lines before pulling
+ before_pull_whl_lines = []
+ if os.path.exists(requirements_file):
+ with open(requirements_file, 'r') as f:
+ before_pull_whl_lines = [line for line in f if '.whl' in line]
+
+ print_big_message('Updating the local copy of the repository with "git pull"')
+
+ # Hash files before pulling
+ files_to_check = [
+ 'start_linux.sh', 'start_macos.sh', 'start_windows.bat', 'start_wsl.bat',
+ 'update_wizard_linux.sh', 'update_wizard_macos.sh', 'update_wizard_windows.bat', 'update_wizard_wsl.bat',
+ 'one_click.py'
+ ]
+ before_hashes = {file: calculate_file_hash(file) for file in files_to_check}
+
+ # Perform the git pull
+ run_cmd("git pull --autostash", assert_success=True, environment=True)
+
+ # Check hashes after pulling
+ after_hashes = {file: calculate_file_hash(file) for file in files_to_check}
+ if os.path.exists(requirements_file):
+ with open(requirements_file, 'r') as f:
+ after_pull_whl_lines = [line for line in f if '.whl' in line]
+
+ wheels_changed = wheels_changed or (before_pull_whl_lines != after_pull_whl_lines)
+
+ # Check for changes to installer files
+ for file in files_to_check:
+ if before_hashes[file] != after_hashes[file]:
+ print_big_message(f"File '{file}' was updated during 'git pull'. Please run the script again.")
+
+ # Save state before exiting
+ state = load_state()
+ if wheels_changed:
+ state['wheels_changed'] = True
+ save_state(state)
+ sys.exit(1)
+
+ # Save current state
+ state = load_state()
+ state['last_installed_commit'] = current_commit
+ state.pop('wheels_changed', None) # Remove wheels_changed flag
+ save_state(state)
+
+ if os.environ.get("INSTALL_EXTENSIONS", "").lower() in ("yes", "y", "true", "1", "t", "on"):
+ install_extensions_requirements()
+
+ if is_linux():
+ run_cmd(f"conda install -y -c conda-forge libstdcxx-ng=={LIBSTDCXX_VERSION_LINUX}", assert_success=True, environment=True)
+
+ # Update PyTorch
+ if not initial_installation:
+ update_pytorch_and_python()
+ clean_outdated_pytorch_cuda_dependencies()
+
+ print_big_message(f"Installing webui requirements from file: {requirements_file}")
+ print(f"GPU Choice: {gpu_choice}\n")
+
+ # Prepare the requirements file
+ textgen_requirements = open(requirements_file).read().splitlines()
+
+ if not initial_installation and not wheels_changed:
+ textgen_requirements = [line for line in textgen_requirements if '.whl' not in line]
+
+ with open('temp_requirements.txt', 'w') as file:
+ file.write('\n'.join(textgen_requirements))
+
+ # Workaround for git+ packages not updating properly.
+ git_requirements = [req for req in textgen_requirements if req.startswith("git+")]
+ for req in git_requirements:
+ url = req.replace("git+", "")
+ package_name = url.split("/")[-1].split("@")[0].rstrip(".git")
+ run_cmd(f"python -m pip uninstall -y {package_name}", environment=True)
+ print(f"Uninstalled {package_name}")
+
+ # Install/update the project requirements
+ run_cmd("python -m pip install -r temp_requirements.txt --upgrade", assert_success=True, environment=True)
+
+ # Clean up
+ os.remove('temp_requirements.txt')
+ clear_cache()
+
+
+def install_extensions_requirements():
+ print_big_message("Installing extensions requirements.\nSome of these may fail on Windows.\nDon\'t worry if you see error messages, as they will not affect the main program.")
+ extensions = get_extensions_names()
+ for i, extension in enumerate(extensions):
+ print(f"\n\n--- [{i + 1}/{len(extensions)}]: {extension}\n\n")
+ extension_req_path = os.path.join("extensions", extension, "requirements.txt")
+ run_cmd(f"python -m pip install -r {extension_req_path} --upgrade", assert_success=False, environment=True)
+
+
+def launch_webui():
+ run_cmd(f"python server.py {flags}", environment=True)
+
+
+if __name__ == "__main__":
+ # Verifies we are in a conda environment
+ check_env()
+
+ parser = argparse.ArgumentParser(add_help=False)
+ parser.add_argument('--update-wizard', action='store_true', help='Launch a menu with update options.')
+ args, _ = parser.parse_known_args()
+
+ if args.update_wizard:
+ while True:
+ choice = get_user_choice(
+ "What would you like to do?",
+ {
+ 'A': 'Update the web UI',
+ 'B': 'Install/update extensions requirements',
+ 'C': 'Revert local changes to repository files with \"git reset --hard\"',
+ 'N': 'Nothing (exit)'
+ },
+ )
+
+ if choice == 'A':
+ update_requirements()
+ elif choice == 'B':
+ choices = {'A': 'All extensions'}
+ for i, name in enumerate(get_extensions_names()):
+ key = generate_alphabetic_sequence(i + 1)
+ choices[key] = name
+
+ choice = get_user_choice("What extension?", choices)
+
+ if choice == 'A':
+ install_extensions_requirements()
+ else:
+ extension_req_path = os.path.join("extensions", choices[choice], "requirements.txt")
+ run_cmd(f"python -m pip install -r {extension_req_path} --upgrade", assert_success=False, environment=True)
+
+ update_requirements(pull=False)
+ elif choice == 'C':
+ run_cmd("git reset --hard", assert_success=True, environment=True)
+ elif choice == 'N':
+ sys.exit()
+ else:
+ if not is_installed():
+ install_webui()
+ os.chdir(script_dir)
+
+ if os.environ.get("LAUNCH_AFTER_INSTALL", "").lower() in ("no", "n", "false", "0", "f", "off"):
+ print_big_message("Will now exit due to LAUNCH_AFTER_INSTALL.")
+ sys.exit()
+
+ # Check if a model has been downloaded yet
+ if '--model-dir' in flags:
+ # Splits on ' ' or '=' while maintaining spaces within quotes
+ flags_list = re.split(' +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)|=', flags)
+ model_dir = [flags_list[(flags_list.index(flag) + 1)] for flag in flags_list if flag == '--model-dir'][0].strip('"\'')
+ else:
+ model_dir = 'user_data/models'
+
+ if len([item for item in glob.glob(f'{model_dir}/*') if not item.endswith(('.txt', '.yaml'))]) == 0:
+ print_big_message("You haven't downloaded any model yet.\nOnce the web UI launches, head over to the \"Model\" tab and download one.")
+
+ # Workaround for llama-cpp-python loading paths in CUDA env vars even if they do not exist
+ conda_path_bin = os.path.join(conda_env_path, "bin")
+ if not os.path.exists(conda_path_bin):
+ os.mkdir(conda_path_bin)
+
+ # Launch the webui
+ launch_webui()
diff --git a/requirements/full/requirements.txt b/requirements/full/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..97eac769aefd83fff1d41680d99809170139e238
--- /dev/null
+++ b/requirements/full/requirements.txt
@@ -0,0 +1,47 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+bitsandbytes==0.48.*
+colorama
+datasets
+einops
+fastapi==0.112.4
+flash-linear-attention==0.3.2
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.3.1.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# CUDA wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124-py3-none-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav3/releases/download/v0.0.7/exllamav3-0.0.7+cu128.torch2.7.0-cp311-cp311-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav3/releases/download/v0.0.7/exllamav3-0.0.7+cu128.torch2.7.0-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2+cu128.torch2.7.0-cp311-cp311-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2+cu128.torch2.7.0-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2-py3-none-any.whl; platform_system == "Linux" and platform_machine != "x86_64"
+https://github.com/kingbri1/flash-attention/releases/download/v2.8.3/flash_attn-2.8.3+cu128torch2.7.0cxx11abiFALSE-cp311-cp311-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.3/flash_attn-2.8.3+cu12torch2.7cxx11abiFALSE-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
diff --git a/requirements/full/requirements_amd.txt b/requirements/full/requirements_amd.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b3b0005e09f2f2a63f7c6580701ab09459e3a7de
--- /dev/null
+++ b/requirements/full/requirements_amd.txt
@@ -0,0 +1,40 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+colorama
+datasets
+einops
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.2.0.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# AMD wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkan-py3-none-win_amd64.whl; platform_system == "Windows"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkan-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2+rocm6.2.4.torch2.6.0-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2-py3-none-any.whl; platform_system != "Darwin" and platform_machine != "x86_64"
diff --git a/requirements/full/requirements_amd_noavx2.txt b/requirements/full/requirements_amd_noavx2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5e0d375e85c0139ab3c918908adc727ef06a6963
--- /dev/null
+++ b/requirements/full/requirements_amd_noavx2.txt
@@ -0,0 +1,40 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+colorama
+datasets
+einops
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.2.0.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# AMD wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkanavx-py3-none-win_amd64.whl; platform_system == "Windows"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkanavx-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2+rocm6.2.4.torch2.6.0-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2-py3-none-any.whl; platform_system != "Darwin" and platform_machine != "x86_64"
diff --git a/requirements/full/requirements_apple_intel.txt b/requirements/full/requirements_apple_intel.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0bb837ba930a94f6004c892a1cd08a4ecb699729
--- /dev/null
+++ b/requirements/full/requirements_apple_intel.txt
@@ -0,0 +1,38 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+colorama
+datasets
+einops
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.2.0.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# Mac wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_15_0_x86_64.whl; platform_system == "Darwin" and platform_release >= "24.0.0" and platform_release < "25.0.0" and python_version == "3.11"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_14_0_x86_64.whl; platform_system == "Darwin" and platform_release >= "23.0.0" and platform_release < "24.0.0" and python_version == "3.11"
diff --git a/requirements/full/requirements_apple_silicon.txt b/requirements/full/requirements_apple_silicon.txt
new file mode 100644
index 0000000000000000000000000000000000000000..514c0662000590d1545ba4ff19d4f8165c8ebd88
--- /dev/null
+++ b/requirements/full/requirements_apple_silicon.txt
@@ -0,0 +1,39 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+colorama
+datasets
+einops
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.2.0.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# Mac wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_15_0_arm64.whl; platform_system == "Darwin" and platform_release >= "24.0.0" and platform_release < "25.0.0" and python_version == "3.11"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_14_0_arm64.whl; platform_system == "Darwin" and platform_release >= "23.0.0" and platform_release < "24.0.0" and python_version == "3.11"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_13_0_arm64.whl; platform_system == "Darwin" and platform_release >= "22.0.0" and platform_release < "23.0.0" and python_version == "3.11"
diff --git a/requirements/full/requirements_cpu_only.txt b/requirements/full/requirements_cpu_only.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f68fdd9da158e2b095a2c4c6de8bcc65726fa167
--- /dev/null
+++ b/requirements/full/requirements_cpu_only.txt
@@ -0,0 +1,38 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+colorama
+datasets
+einops
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.2.0.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# llama.cpp (CPU only, AVX2)
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx2-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx2-py3-none-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
diff --git a/requirements/full/requirements_cpu_only_noavx2.txt b/requirements/full/requirements_cpu_only_noavx2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b40f1af21661b38104ff87a24bc57cc123130425
--- /dev/null
+++ b/requirements/full/requirements_cpu_only_noavx2.txt
@@ -0,0 +1,38 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+colorama
+datasets
+einops
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.2.0.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# llama.cpp (CPU only, no AVX2)
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx-py3-none-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
diff --git a/requirements/full/requirements_noavx2.txt b/requirements/full/requirements_noavx2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..9de9e65aaaf4954ec8889f89c941cc28c94b321a
--- /dev/null
+++ b/requirements/full/requirements_noavx2.txt
@@ -0,0 +1,47 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+bitsandbytes==0.48.*
+colorama
+datasets
+einops
+fastapi==0.112.4
+flash-linear-attention==0.3.2
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.3.1.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# CUDA wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124avx-py3-none-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124avx-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav3/releases/download/v0.0.7/exllamav3-0.0.7+cu128.torch2.7.0-cp311-cp311-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav3/releases/download/v0.0.7/exllamav3-0.0.7+cu128.torch2.7.0-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2+cu128.torch2.7.0-cp311-cp311-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2+cu128.torch2.7.0-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
+https://github.com/turboderp-org/exllamav2/releases/download/v0.3.2/exllamav2-0.3.2-py3-none-any.whl; platform_system == "Linux" and platform_machine != "x86_64"
+https://github.com/kingbri1/flash-attention/releases/download/v2.8.3/flash_attn-2.8.3+cu128torch2.7.0cxx11abiFALSE-cp311-cp311-win_amd64.whl; platform_system == "Windows" and python_version == "3.11"
+https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.3/flash_attn-2.8.3+cu12torch2.7cxx11abiFALSE-cp311-cp311-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64" and python_version == "3.11"
diff --git a/requirements/full/requirements_nowheels.txt b/requirements/full/requirements_nowheels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3bd20dd9c8fed4ff1c2ae869898d772c09c20049
--- /dev/null
+++ b/requirements/full/requirements_nowheels.txt
@@ -0,0 +1,34 @@
+accelerate==1.8.*
+audioop-lts<1.0; python_version >= "3.13"
+colorama
+datasets
+einops
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pandas
+peft==0.17.*
+Pillow>=9.5.0
+psutil
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+safetensors==0.6.*
+scipy
+sentencepiece
+tensorboard
+transformers==4.57.*
+triton-windows==3.2.0.post19; platform_system == "Windows"
+tqdm
+wandb
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
diff --git a/requirements/portable/requirements.txt b/requirements/portable/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7a38b1e6eb338769848e98fce6b002317df4f14d
--- /dev/null
+++ b/requirements/portable/requirements.txt
@@ -0,0 +1,23 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# CUDA wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124-py3-none-win_amd64.whl; platform_system == "Windows"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
diff --git a/requirements/portable/requirements_apple_intel.txt b/requirements/portable/requirements_apple_intel.txt
new file mode 100644
index 0000000000000000000000000000000000000000..047d1c54761dd4233416f0dcf1acd36141ece5e2
--- /dev/null
+++ b/requirements/portable/requirements_apple_intel.txt
@@ -0,0 +1,24 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# Mac wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_15_0_x86_64.whl; platform_system == "Darwin" and platform_release >= "24.0.0" and platform_release < "25.0.0"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_14_0_x86_64.whl; platform_system == "Darwin" and platform_release >= "23.0.0" and platform_release < "24.0.0"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_13_0_x86_64.whl; platform_system == "Darwin" and platform_release >= "22.0.0" and platform_release < "23.0.0"
\ No newline at end of file
diff --git a/requirements/portable/requirements_apple_silicon.txt b/requirements/portable/requirements_apple_silicon.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5c8ae4df94d4c2a29e04741bce7b4426ce33ca21
--- /dev/null
+++ b/requirements/portable/requirements_apple_silicon.txt
@@ -0,0 +1,24 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# Mac wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_15_0_arm64.whl; platform_system == "Darwin" and platform_release >= "24.0.0" and platform_release < "25.0.0"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_14_0_arm64.whl; platform_system == "Darwin" and platform_release >= "23.0.0" and platform_release < "24.0.0"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0-py3-none-macosx_13_0_arm64.whl; platform_system == "Darwin" and platform_release >= "22.0.0" and platform_release < "23.0.0"
diff --git a/requirements/portable/requirements_cpu_only.txt b/requirements/portable/requirements_cpu_only.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f41efd586662c1098487ebaa6857f65767975cbc
--- /dev/null
+++ b/requirements/portable/requirements_cpu_only.txt
@@ -0,0 +1,23 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# llama.cpp (CPU only, AVX2)
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx2-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx2-py3-none-win_amd64.whl; platform_system == "Windows"
diff --git a/requirements/portable/requirements_cpu_only_noavx2.txt b/requirements/portable/requirements_cpu_only_noavx2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..69158050960f29f2bf35b80013600e678494cea8
--- /dev/null
+++ b/requirements/portable/requirements_cpu_only_noavx2.txt
@@ -0,0 +1,23 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# llama.cpp (CPU only, no AVX2)
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cpuavx-py3-none-win_amd64.whl; platform_system == "Windows"
diff --git a/requirements/portable/requirements_noavx2.txt b/requirements/portable/requirements_noavx2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ca66098c379272e5f061bccc12d5ef2722baab56
--- /dev/null
+++ b/requirements/portable/requirements_noavx2.txt
@@ -0,0 +1,23 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# CUDA wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124avx-py3-none-win_amd64.whl; platform_system == "Windows"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+cu124avx-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
diff --git a/requirements/portable/requirements_nowheels.txt b/requirements/portable/requirements_nowheels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..be624bb1e5f45ff624e3db8cf9032643ef16d05f
--- /dev/null
+++ b/requirements/portable/requirements_nowheels.txt
@@ -0,0 +1,19 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
diff --git a/requirements/portable/requirements_vulkan.txt b/requirements/portable/requirements_vulkan.txt
new file mode 100644
index 0000000000000000000000000000000000000000..36aff3617a3602c153dbef89cfd50eeffee36151
--- /dev/null
+++ b/requirements/portable/requirements_vulkan.txt
@@ -0,0 +1,23 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# CUDA wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkan-py3-none-win_amd64.whl; platform_system == "Windows"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkan-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
diff --git a/requirements/portable/requirements_vulkan_noavx2.txt b/requirements/portable/requirements_vulkan_noavx2.txt
new file mode 100644
index 0000000000000000000000000000000000000000..be7170e3d585cbfb593b8869089d4de5fd994146
--- /dev/null
+++ b/requirements/portable/requirements_vulkan_noavx2.txt
@@ -0,0 +1,23 @@
+audioop-lts<1.0; python_version >= "3.13"
+fastapi==0.112.4
+gradio==4.37.*
+html2text==2025.4.15
+jinja2==3.1.6
+markdown
+numpy==2.2.*
+pydantic==2.8.2
+PyPDF2==3.0.1
+python-docx==1.1.2
+pyyaml
+requests
+rich
+tqdm
+
+# API
+flask_cloudflared==0.0.14
+sse-starlette==1.6.5
+tiktoken
+
+# CUDA wheels
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkanavx-py3-none-win_amd64.whl; platform_system == "Windows"
+https://github.com/oobabooga/llama-cpp-binaries/releases/download/v0.49.0/llama_cpp_binaries-0.49.0+vulkanavx-py3-none-linux_x86_64.whl; platform_system == "Linux" and platform_machine == "x86_64"
diff --git a/server.py b/server.py
new file mode 100644
index 0000000000000000000000000000000000000000..c804c342328eee9495be20e9e17c91609968936a
--- /dev/null
+++ b/server.py
@@ -0,0 +1,338 @@
+import os
+import shutil
+import warnings
+from pathlib import Path
+
+from modules import shared
+from modules.block_requests import OpenMonkeyPatch, RequestBlocker
+from modules.logging_colors import logger
+from modules.prompts import load_prompt
+
+# Set up Gradio temp directory path
+gradio_temp_path = Path('user_data') / 'cache' / 'gradio'
+shutil.rmtree(gradio_temp_path, ignore_errors=True)
+gradio_temp_path.mkdir(parents=True, exist_ok=True)
+
+# Set environment variables
+os.environ.update({
+ 'GRADIO_ANALYTICS_ENABLED': 'False',
+ 'BITSANDBYTES_NOWELCOME': '1',
+ 'GRADIO_TEMP_DIR': str(gradio_temp_path)
+})
+
+warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
+warnings.filterwarnings('ignore', category=UserWarning, message='Using the update method is deprecated')
+warnings.filterwarnings('ignore', category=UserWarning, message='Field "model_name" has conflict')
+warnings.filterwarnings('ignore', category=UserWarning, message='The value passed into gr.Dropdown()')
+warnings.filterwarnings('ignore', category=UserWarning, message='Field "model_names" has conflict')
+
+with RequestBlocker():
+ from modules import gradio_hijack
+ import gradio as gr
+
+import matplotlib
+
+matplotlib.use('Agg') # This fixes LaTeX rendering on some systems
+
+import os
+import signal
+import sys
+import time
+from functools import partial
+from threading import Lock, Thread
+
+import yaml
+
+import modules.extensions as extensions_module
+from modules import (
+ training,
+ ui,
+ ui_chat,
+ ui_default,
+ ui_file_saving,
+ ui_model_menu,
+ ui_notebook,
+ ui_parameters,
+ ui_session,
+ utils
+)
+from modules.chat import generate_pfp_cache
+from modules.extensions import apply_extensions
+from modules.LoRA import add_lora_to_model
+from modules.models import load_model, unload_model_if_idle
+from modules.models_settings import (
+ get_fallback_settings,
+ get_model_metadata,
+ update_gpu_layers_and_vram,
+ update_model_parameters
+)
+from modules.shared import do_cmd_flags_warnings
+from modules.utils import gradio
+
+
+def signal_handler(sig, frame):
+ logger.info("Received Ctrl+C. Shutting down Text Generation Web UI gracefully.")
+
+ # Explicitly stop LlamaServer to avoid __del__ cleanup issues during shutdown
+ if shared.model and shared.model.__class__.__name__ == 'LlamaServer':
+ try:
+ shared.model.stop()
+ except:
+ pass
+
+ sys.exit(0)
+
+
+signal.signal(signal.SIGINT, signal_handler)
+
+
+def create_interface():
+
+ title = 'Text Generation Web UI'
+
+ # Password authentication
+ auth = []
+ if shared.args.gradio_auth:
+ auth.extend(x.strip() for x in shared.args.gradio_auth.strip('"').replace('\n', '').split(',') if x.strip())
+ if shared.args.gradio_auth_path:
+ with open(shared.args.gradio_auth_path, 'r', encoding="utf8") as file:
+ auth.extend(x.strip() for line in file for x in line.split(',') if x.strip())
+ auth = [tuple(cred.split(':')) for cred in auth]
+
+ # Import the extensions and execute their setup() functions
+ if shared.args.extensions is not None and len(shared.args.extensions) > 0:
+ extensions_module.load_extensions()
+
+ # Force some events to be triggered on page load
+ shared.persistent_interface_state.update({
+ 'mode': shared.settings['mode'],
+ 'loader': shared.args.loader or 'llama.cpp',
+ 'filter_by_loader': (shared.args.loader or 'All') if not shared.args.portable else 'llama.cpp'
+ })
+
+ if shared.settings['prompt-notebook']:
+ prompt = load_prompt(shared.settings['prompt-notebook'])
+ shared.persistent_interface_state.update({
+ 'textbox-default': prompt,
+ 'textbox-notebook': prompt
+ })
+
+ # Clear existing cache files
+ for cache_file in ['pfp_character.png', 'pfp_character_thumb.png']:
+ cache_path = Path(f"user_data/cache/{cache_file}")
+ if cache_path.exists():
+ cache_path.unlink()
+
+ # Regenerate for default character
+ if shared.settings['mode'] != 'instruct':
+ generate_pfp_cache(shared.settings['character'])
+
+ # css/js strings
+ css = ui.css
+ js = ui.js
+ css += apply_extensions('css')
+ js += apply_extensions('js')
+
+ # Interface state elements
+ shared.input_elements = ui.list_interface_input_elements()
+
+ with gr.Blocks(css=css, analytics_enabled=False, title=title, theme=ui.theme) as shared.gradio['interface']:
+
+ # Interface state
+ shared.gradio['interface_state'] = gr.State({k: None for k in shared.input_elements})
+
+ # Audio notification
+ if Path("user_data/notification.mp3").exists():
+ shared.gradio['audio_notification'] = gr.Audio(interactive=False, value="user_data/notification.mp3", elem_id="audio_notification", visible=False)
+
+ # Floating menus for saving/deleting files
+ ui_file_saving.create_ui()
+
+ # Temporary clipboard for saving files
+ shared.gradio['temporary_text'] = gr.Textbox(visible=False)
+
+ # Chat tab
+ ui_chat.create_ui()
+
+ # Notebook tab
+ with gr.Tab("Notebook", elem_id='notebook-parent-tab'):
+ ui_default.create_ui()
+ ui_notebook.create_ui()
+
+ ui_parameters.create_ui() # Parameters tab
+ ui_chat.create_character_settings_ui() # Character tab
+ ui_model_menu.create_ui() # Model tab
+ if not shared.args.portable:
+ training.create_ui() # Training tab
+ ui_session.create_ui() # Session tab
+
+ # Generation events
+ ui_chat.create_event_handlers()
+ ui_default.create_event_handlers()
+ ui_notebook.create_event_handlers()
+
+ # Other events
+ ui_file_saving.create_event_handlers()
+ ui_parameters.create_event_handlers()
+ ui_model_menu.create_event_handlers()
+
+ # UI persistence events
+ ui.setup_auto_save()
+
+ # Interface launch events
+ shared.gradio['interface'].load(
+ None,
+ gradio('show_controls'),
+ None,
+ js=f"""(x) => {{
+ // Check if this is first visit or if localStorage is out of sync
+ const savedTheme = localStorage.getItem('theme');
+ const serverTheme = {str(shared.settings['dark_theme']).lower()} ? 'dark' : 'light';
+
+ // If no saved theme or mismatch with server on first load, use server setting
+ if (!savedTheme || !sessionStorage.getItem('theme_synced')) {{
+ localStorage.setItem('theme', serverTheme);
+ sessionStorage.setItem('theme_synced', 'true');
+ if (serverTheme === 'dark') {{
+ document.getElementsByTagName('body')[0].classList.add('dark');
+ }} else {{
+ document.getElementsByTagName('body')[0].classList.remove('dark');
+ }}
+ }} else {{
+ // Use localStorage for subsequent reloads
+ if (savedTheme === 'dark') {{
+ document.getElementsByTagName('body')[0].classList.add('dark');
+ }} else {{
+ document.getElementsByTagName('body')[0].classList.remove('dark');
+ }}
+ }}
+ {js}
+ {ui.show_controls_js}
+ toggle_controls(x);
+ }}"""
+ )
+
+ shared.gradio['interface'].load(partial(ui.apply_interface_values, {}, use_persistent=True), None, gradio(ui.list_interface_input_elements()), show_progress=False)
+
+ extensions_module.create_extensions_tabs() # Extensions tabs
+ extensions_module.create_extensions_block() # Extensions block
+
+ # Launch the interface
+ shared.gradio['interface'].queue()
+ with OpenMonkeyPatch():
+ shared.gradio['interface'].launch(
+ max_threads=64,
+ prevent_thread_lock=True,
+ share=shared.args.share,
+ server_name=None if not shared.args.listen else (shared.args.listen_host or '0.0.0.0'),
+ server_port=shared.args.listen_port,
+ inbrowser=shared.args.auto_launch,
+ auth=auth or None,
+ ssl_verify=False if (shared.args.ssl_keyfile or shared.args.ssl_certfile) else True,
+ ssl_keyfile=shared.args.ssl_keyfile,
+ ssl_certfile=shared.args.ssl_certfile,
+ root_path=shared.args.subpath,
+ allowed_paths=["css", "js", "extensions", "user_data/cache"]
+ )
+
+
+if __name__ == "__main__":
+
+ logger.info("Starting Text Generation Web UI")
+ do_cmd_flags_warnings()
+
+ # Load custom settings
+ settings_file = None
+ if shared.args.settings is not None and Path(shared.args.settings).exists():
+ settings_file = Path(shared.args.settings)
+ elif Path('user_data/settings.yaml').exists():
+ settings_file = Path('user_data/settings.yaml')
+
+ if settings_file is not None:
+ logger.info(f"Loading settings from \"{settings_file}\"")
+ with open(settings_file, 'r', encoding='utf-8') as f:
+ new_settings = yaml.safe_load(f.read())
+
+ if new_settings:
+ shared.settings.update(new_settings)
+
+ # Fallback settings for models
+ shared.model_config['.*'] = get_fallback_settings()
+ shared.model_config.move_to_end('.*', last=False) # Move to the beginning
+
+ # Activate the extensions listed on settings.yaml
+ extensions_module.available_extensions = utils.get_available_extensions()
+ for extension in shared.settings['default_extensions']:
+ shared.args.extensions = shared.args.extensions or []
+ if extension not in shared.args.extensions:
+ shared.args.extensions.append(extension)
+
+ available_models = utils.get_available_models()
+
+ # Model defined through --model
+ if shared.args.model is not None:
+ shared.model_name = shared.args.model
+
+ # Select the model from a command-line menu
+ elif shared.args.model_menu:
+ if len(available_models) == 0:
+ logger.error('No models are available! Please download at least one.')
+ sys.exit(0)
+ else:
+ print('The following models are available:\n')
+ for i, model in enumerate(available_models):
+ print(f'{i+1}. {model}')
+
+ print(f'\nWhich one do you want to load? 1-{len(available_models)}\n')
+ i = int(input()) - 1
+ print()
+
+ shared.model_name = available_models[i]
+
+ # If any model has been selected, load it
+ if shared.model_name != 'None':
+ model_settings = get_model_metadata(shared.model_name)
+ update_model_parameters(model_settings, initial=True) # hijack the command-line arguments
+
+ # Auto-adjust GPU layers if not provided by user and it's a llama.cpp model
+ if 'gpu_layers' not in shared.provided_arguments and shared.args.loader == 'llama.cpp' and 'gpu_layers' in model_settings:
+ vram_usage, adjusted_layers = update_gpu_layers_and_vram(
+ shared.args.loader,
+ shared.model_name,
+ model_settings['gpu_layers'],
+ shared.args.ctx_size,
+ shared.args.cache_type,
+ auto_adjust=True,
+ for_ui=False
+ )
+
+ shared.args.gpu_layers = adjusted_layers
+
+ # Load the model
+ shared.model, shared.tokenizer = load_model(shared.model_name)
+ if shared.args.lora:
+ add_lora_to_model(shared.args.lora)
+
+ shared.generation_lock = Lock()
+
+ if shared.args.idle_timeout > 0:
+ timer_thread = Thread(target=unload_model_if_idle)
+ timer_thread.daemon = True
+ timer_thread.start()
+
+ if shared.args.nowebui:
+ # Start the API in standalone mode
+ shared.args.extensions = [x for x in (shared.args.extensions or []) if x != 'gallery']
+ if shared.args.extensions:
+ extensions_module.load_extensions()
+ else:
+ # Launch the web UI
+ create_interface()
+ while True:
+ time.sleep(0.5)
+ if shared.need_restart:
+ shared.need_restart = False
+ time.sleep(0.5)
+ shared.gradio['interface'].close()
+ time.sleep(0.5)
+ create_interface()
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..68909d6f06802555c6b28fee09ac10e4ca8a3464
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,3 @@
+[pycodestyle]
+max-line-length = 120
+ignore = E402, E501, E722
\ No newline at end of file
diff --git a/start_linux.sh b/start_linux.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a991e1bc9f008f5cb5676ca0a28e5426d35c51ad
--- /dev/null
+++ b/start_linux.sh
@@ -0,0 +1,77 @@
+#!/usr/bin/env bash
+
+# environment isolation
+export PYTHONNOUSERSITE=1
+unset PYTHONPATH
+unset PYTHONHOME
+
+cd "$(dirname "${BASH_SOURCE[0]}")"
+
+# Portable install case
+if [ -d "portable_env" ]; then
+ ./portable_env/bin/python3 server.py --portable --api --auto-launch "$@"
+ exit $?
+fi
+
+if [[ "$(pwd)" =~ " " ]]; then echo This script relies on Miniforge which can not be silently installed under a path with spaces. && exit; fi
+
+# deactivate existing conda envs as needed to avoid conflicts
+{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
+
+OS_ARCH=$(uname -m)
+case "${OS_ARCH}" in
+ x86_64*) OS_ARCH="x86_64";;
+ arm64*) OS_ARCH="aarch64";;
+ aarch64*) OS_ARCH="aarch64";;
+ *) echo "Unknown system architecture: $OS_ARCH! This script runs only on x86_64 or arm64" && exit
+esac
+
+# config
+INSTALL_DIR="$(pwd)/installer_files"
+CONDA_ROOT_PREFIX="$(pwd)/installer_files/conda"
+INSTALL_ENV_DIR="$(pwd)/installer_files/env"
+MINIFORGE_DOWNLOAD_URL="https://github.com/conda-forge/miniforge/releases/download/25.3.0-3/Miniforge3-25.3.0-3-Linux-${OS_ARCH}.sh"
+conda_exists="F"
+
+# figure out whether git and conda needs to be installed
+if "$CONDA_ROOT_PREFIX/bin/conda" --version &>/dev/null; then conda_exists="T"; fi
+
+# (if necessary) install git and conda into a contained environment
+# download miniforge
+if [ "$conda_exists" == "F" ]; then
+ echo "Downloading Miniforge from $MINIFORGE_DOWNLOAD_URL to $INSTALL_DIR/miniforge_installer.sh"
+
+ mkdir -p "$INSTALL_DIR"
+ curl -L "$MINIFORGE_DOWNLOAD_URL" > "$INSTALL_DIR/miniforge_installer.sh"
+
+ chmod u+x "$INSTALL_DIR/miniforge_installer.sh"
+ bash "$INSTALL_DIR/miniforge_installer.sh" -b -p $CONDA_ROOT_PREFIX
+
+ # test the conda binary
+ echo "Miniforge version:"
+ "$CONDA_ROOT_PREFIX/bin/conda" --version
+
+ # delete the Miniforge installer
+ rm "$INSTALL_DIR/miniforge_installer.sh"
+fi
+
+# create the installer env
+if [ ! -e "$INSTALL_ENV_DIR" ]; then
+ "$CONDA_ROOT_PREFIX/bin/conda" create -y -k --prefix "$INSTALL_ENV_DIR" python=3.11
+fi
+
+# check if conda environment was actually created
+if [ ! -e "$INSTALL_ENV_DIR/bin/python" ]; then
+ echo "Conda environment is empty."
+ exit
+fi
+
+export CUDA_PATH="$INSTALL_ENV_DIR"
+export CUDA_HOME="$CUDA_PATH"
+
+# activate installer env
+source "$CONDA_ROOT_PREFIX/etc/profile.d/conda.sh" # otherwise conda complains about 'shell not initialized' (needed when running in a script)
+conda activate "$INSTALL_ENV_DIR"
+
+# setup installer env
+python one_click.py $@
diff --git a/start_macos.sh b/start_macos.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6426229abd07c753ec7205449f1138e9203071ef
--- /dev/null
+++ b/start_macos.sh
@@ -0,0 +1,77 @@
+#!/bin/bash
+
+# environment isolation
+export PYTHONNOUSERSITE=1
+unset PYTHONPATH
+unset PYTHONHOME
+
+cd "$(dirname "${BASH_SOURCE[0]}")"
+
+# Portable install case
+if [ -d "portable_env" ]; then
+ ./portable_env/bin/python3 server.py --portable --api --auto-launch --api-port 5005 "$@"
+ exit $?
+fi
+
+if [[ "$(pwd)" =~ " " ]]; then echo This script relies on Miniforge which can not be silently installed under a path with spaces. && exit; fi
+
+# deactivate existing conda envs as needed to avoid conflicts
+{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
+
+# M Series or Intel
+OS_ARCH=$(uname -m)
+case "${OS_ARCH}" in
+ x86_64*) OS_ARCH="x86_64";;
+ arm64*) OS_ARCH="arm64";;
+ *) echo "Unknown system architecture: $OS_ARCH! This script runs only on x86_64 or arm64" && exit
+esac
+
+# config
+INSTALL_DIR="$(pwd)/installer_files"
+CONDA_ROOT_PREFIX="$(pwd)/installer_files/conda"
+INSTALL_ENV_DIR="$(pwd)/installer_files/env"
+MINIFORGE_DOWNLOAD_URL="https://github.com/conda-forge/miniforge/releases/download/25.3.0-3/Miniforge3-25.3.0-3-MacOSX-${OS_ARCH}.sh"
+conda_exists="F"
+
+# figure out whether git and conda needs to be installed
+if "$CONDA_ROOT_PREFIX/bin/conda" --version &>/dev/null; then conda_exists="T"; fi
+
+# (if necessary) install git and conda into a contained environment
+# download miniforge
+if [ "$conda_exists" == "F" ]; then
+ echo "Downloading Miniforge from $MINIFORGE_DOWNLOAD_URL to $INSTALL_DIR/miniforge_installer.sh"
+
+ mkdir -p "$INSTALL_DIR"
+ curl -L "$MINIFORGE_DOWNLOAD_URL" > "$INSTALL_DIR/miniforge_installer.sh"
+
+ chmod u+x "$INSTALL_DIR/miniforge_installer.sh"
+ bash "$INSTALL_DIR/miniforge_installer.sh" -b -p $CONDA_ROOT_PREFIX
+
+ # test the conda binary
+ echo "Miniforge version:"
+ "$CONDA_ROOT_PREFIX/bin/conda" --version
+
+ # delete the Miniforge installer
+ rm "$INSTALL_DIR/miniforge_installer.sh"
+fi
+
+# create the installer env
+if [ ! -e "$INSTALL_ENV_DIR" ]; then
+ "$CONDA_ROOT_PREFIX/bin/conda" create -y -k --prefix "$INSTALL_ENV_DIR" python=3.11
+fi
+
+# check if conda environment was actually created
+if [ ! -e "$INSTALL_ENV_DIR/bin/python" ]; then
+ echo "Conda environment is empty."
+ exit
+fi
+
+export CUDA_PATH="$INSTALL_ENV_DIR"
+export CUDA_HOME="$CUDA_PATH"
+
+# activate installer env
+source "$CONDA_ROOT_PREFIX/etc/profile.d/conda.sh" # otherwise conda complains about 'shell not initialized' (needed when running in a script)
+conda activate "$INSTALL_ENV_DIR"
+
+# setup installer env
+python one_click.py $@
diff --git a/start_windows.bat b/start_windows.bat
new file mode 100644
index 0000000000000000000000000000000000000000..68c6194e76cc7dbbaedb80f88315c88ea056ac49
--- /dev/null
+++ b/start_windows.bat
@@ -0,0 +1,116 @@
+@echo off
+setlocal enabledelayedexpansion
+
+@rem environment isolation
+set PYTHONNOUSERSITE=1
+set PYTHONPATH=
+set PYTHONHOME=
+
+cd /D "%~dp0"
+
+@rem Portable install case
+if exist "portable_env" (
+ .\portable_env\python.exe server.py --portable --api --auto-launch %*
+ exit /b %errorlevel%
+)
+
+set PATH=%PATH%;%SystemRoot%\system32
+
+echo "%CD%"| findstr /C:" " >nul && echo This script relies on Miniforge which can not be silently installed under a path with spaces. && goto end
+
+@rem Check for special characters in installation path
+set "SPCHARMESSAGE="WARNING: Special characters were detected in the installation path!" " This can cause the installation to fail!""
+echo "%CD%"| findstr /R /C:"[!#\$%&()\*+,;<=>?@\[\]\^`{|}~]" >nul && (
+ call :PrintBigMessage %SPCHARMESSAGE%
+)
+set SPCHARMESSAGE=
+
+@rem fix failed install when installing to a separate drive
+set TMP=%cd%\installer_files
+set TEMP=%cd%\installer_files
+
+@rem deactivate existing conda envs as needed to avoid conflicts
+(call conda deactivate && call conda deactivate && call conda deactivate) 2>nul
+
+@rem config
+set INSTALL_DIR=%cd%\installer_files
+set CONDA_ROOT_PREFIX=%cd%\installer_files\conda
+set INSTALL_ENV_DIR=%cd%\installer_files\env
+set MINIFORGE_DOWNLOAD_URL=https://github.com/conda-forge/miniforge/releases/download/25.3.0-3/Miniforge3-25.3.0-3-Windows-x86_64.exe
+set MINIFORGE_CHECKSUM=b48cd98430170983076dfb51769a6d37668176f59bf3b59c4b21ac4c9bc24f39
+set conda_exists=F
+
+@rem figure out whether git and conda needs to be installed
+call "%CONDA_ROOT_PREFIX%\_conda.exe" --version >nul 2>&1
+if "%ERRORLEVEL%" EQU "0" set conda_exists=T
+
+@rem (if necessary) install git and conda into a contained environment
+@rem download conda
+if "%conda_exists%" == "F" (
+ echo Downloading Miniforge from %MINIFORGE_DOWNLOAD_URL% to %INSTALL_DIR%\miniforge_installer.exe
+
+ mkdir "%INSTALL_DIR%"
+ call curl -Lk "%MINIFORGE_DOWNLOAD_URL%" > "%INSTALL_DIR%\miniforge_installer.exe" || ( echo. && echo Miniforge failed to download. && goto end )
+
+ @rem Try CertUtil first
+ for /f %%a in ('CertUtil -hashfile "%INSTALL_DIR%\miniforge_installer.exe" SHA256 ^| find /i /v " " ^| find /i "%MINIFORGE_CHECKSUM%"') do (
+ set "output=%%a"
+ )
+
+ @rem If CertUtil fails, try PowerShell
+ if not defined output (
+ for /f %%a in ('powershell -Command "if((Get-FileHash \"%INSTALL_DIR%\miniforge_installer.exe\" -Algorithm SHA256).Hash -eq ''%MINIFORGE_CHECKSUM%''){echo true}"') do (
+ set "output=%%a"
+ )
+ )
+
+ if not defined output (
+ echo The checksum verification for miniforge_installer.exe has failed.
+ del "%INSTALL_DIR%\miniforge_installer.exe"
+ goto end
+ ) else (
+ echo The checksum verification for miniforge_installer.exe has passed successfully.
+ )
+
+ echo Installing Miniforge to %CONDA_ROOT_PREFIX%
+ start /wait "" "%INSTALL_DIR%\miniforge_installer.exe" /InstallationType=JustMe /NoShortcuts=1 /AddToPath=0 /RegisterPython=0 /NoRegistry=1 /S /D=%CONDA_ROOT_PREFIX%
+
+ @rem test the conda binary
+ echo Miniforge version:
+ call "%CONDA_ROOT_PREFIX%\_conda.exe" --version || ( echo. && echo Miniforge not found. && goto end )
+
+ @rem delete the Miniforge installer
+ del "%INSTALL_DIR%\miniforge_installer.exe"
+)
+
+@rem create the installer env
+if not exist "%INSTALL_ENV_DIR%" (
+ echo Packages to install: %PACKAGES_TO_INSTALL%
+ call "%CONDA_ROOT_PREFIX%\_conda.exe" create --no-shortcuts -y -k --prefix "%INSTALL_ENV_DIR%" python=3.11 || ( echo. && echo Conda environment creation failed. && goto end )
+)
+
+@rem check if conda environment was actually created
+if not exist "%INSTALL_ENV_DIR%\python.exe" ( echo. && echo Conda environment is empty. && goto end )
+
+set "CUDA_PATH=%INSTALL_ENV_DIR%"
+set "CUDA_HOME=%CUDA_PATH%"
+
+@rem activate installer env
+call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%" || ( echo. && echo Miniforge hook not found. && goto end )
+
+@rem setup installer env
+call python one_click.py %*
+
+@rem below are functions for the script next line skips these during normal execution
+goto end
+
+:PrintBigMessage
+echo. && echo.
+echo *******************************************************************
+for %%M in (%*) do echo * %%~M
+echo *******************************************************************
+echo. && echo.
+exit /b
+
+:end
+pause
diff --git a/update_wizard_linux.sh b/update_wizard_linux.sh
new file mode 100644
index 0000000000000000000000000000000000000000..eb4a753caf9ca04f93057a4ee7b8a8feeb983e57
--- /dev/null
+++ b/update_wizard_linux.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+
+cd "$(dirname "${BASH_SOURCE[0]}")"
+
+if [[ "$(pwd)" =~ " " ]]; then echo This script relies on Miniforge which can not be silently installed under a path with spaces. && exit; fi
+
+# deactivate existing conda envs as needed to avoid conflicts
+{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
+
+# config
+CONDA_ROOT_PREFIX="$(pwd)/installer_files/conda"
+INSTALL_ENV_DIR="$(pwd)/installer_files/env"
+
+# environment isolation
+export PYTHONNOUSERSITE=1
+unset PYTHONPATH
+unset PYTHONHOME
+export CUDA_PATH="$INSTALL_ENV_DIR"
+export CUDA_HOME="$CUDA_PATH"
+
+# activate installer env
+source "$CONDA_ROOT_PREFIX/etc/profile.d/conda.sh" # otherwise conda complains about 'shell not initialized' (needed when running in a script)
+conda activate "$INSTALL_ENV_DIR"
+
+# update installer env
+python one_click.py --update-wizard && echo -e "\nHave a great day!"
diff --git a/update_wizard_macos.sh b/update_wizard_macos.sh
new file mode 100644
index 0000000000000000000000000000000000000000..61a8110c80e171d6af114042ddcfbfc102f2d125
--- /dev/null
+++ b/update_wizard_macos.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+cd "$(dirname "${BASH_SOURCE[0]}")"
+
+if [[ "$(pwd)" =~ " " ]]; then echo This script relies on Miniforge which can not be silently installed under a path with spaces. && exit; fi
+
+# deactivate existing conda envs as needed to avoid conflicts
+{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
+
+# config
+CONDA_ROOT_PREFIX="$(pwd)/installer_files/conda"
+INSTALL_ENV_DIR="$(pwd)/installer_files/env"
+
+# environment isolation
+export PYTHONNOUSERSITE=1
+unset PYTHONPATH
+unset PYTHONHOME
+export CUDA_PATH="$INSTALL_ENV_DIR"
+export CUDA_HOME="$CUDA_PATH"
+
+# activate installer env
+source "$CONDA_ROOT_PREFIX/etc/profile.d/conda.sh" # otherwise conda complains about 'shell not initialized' (needed when running in a script)
+conda activate "$INSTALL_ENV_DIR"
+
+# update installer env
+python one_click.py --update-wizard && echo -e "\nHave a great day!"
diff --git a/update_wizard_windows.bat b/update_wizard_windows.bat
new file mode 100644
index 0000000000000000000000000000000000000000..e9203c529b75f4a42b7b51127b229d0f877cb40e
--- /dev/null
+++ b/update_wizard_windows.bat
@@ -0,0 +1,37 @@
+@echo off
+
+cd /D "%~dp0"
+
+set PATH=%PATH%;%SystemRoot%\system32
+
+echo "%CD%"| findstr /C:" " >nul && echo This script relies on Miniforge which can not be silently installed under a path with spaces. && goto end
+
+@rem fix failed install when installing to a separate drive
+set TMP=%cd%\installer_files
+set TEMP=%cd%\installer_files
+
+@rem deactivate existing conda envs as needed to avoid conflicts
+(call conda deactivate && call conda deactivate && call conda deactivate) 2>nul
+
+@rem config
+set CONDA_ROOT_PREFIX=%cd%\installer_files\conda
+set INSTALL_ENV_DIR=%cd%\installer_files\env
+
+@rem environment isolation
+set PYTHONNOUSERSITE=1
+set PYTHONPATH=
+set PYTHONHOME=
+set "CUDA_PATH=%INSTALL_ENV_DIR%"
+set "CUDA_HOME=%CUDA_PATH%"
+
+@rem activate installer env
+call "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%" || ( echo. && echo Miniforge hook not found. && goto end )
+
+@rem update installer env
+call python one_click.py --update-wizard && (
+ echo.
+ echo Have a great day!
+)
+
+:end
+pause