Skip to content

Commit 3b41459

Browse files
authored
Merge branch 'oobabooga:main' into stt-extension
2 parents 1c0bda3 + 3375eae commit 3b41459

File tree

15 files changed

+460
-183
lines changed

15 files changed

+460
-183
lines changed

README.md

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Text generation web UI
22

3-
A gradio web UI for running Large Language Models like GPT-J 6B, OPT, GALACTICA, GPT-Neo, and Pygmalion.
3+
A gradio web UI for running Large Language Models like GPT-J 6B, OPT, GALACTICA, LLaMA, and Pygmalion.
44

55
Its goal is to become the [AUTOMATIC1111/stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui) of text generation.
66

@@ -27,6 +27,7 @@ Its goal is to become the [AUTOMATIC1111/stable-diffusion-webui](https://github.
2727
* [FlexGen offload](https://github.com/oobabooga/text-generation-webui/wiki/FlexGen).
2828
* [DeepSpeed ZeRO-3 offload](https://github.com/oobabooga/text-generation-webui/wiki/DeepSpeed).
2929
* Get responses via API, [with](https://github.com/oobabooga/text-generation-webui/blob/main/api-example-streaming.py) or [without](https://github.com/oobabooga/text-generation-webui/blob/main/api-example.py) streaming.
30+
* [Supports the LLaMA model, including 4-bit mode](https://github.com/oobabooga/text-generation-webui/wiki/LLaMA-model).
3031
* [Supports the RWKV model](https://github.com/oobabooga/text-generation-webui/wiki/RWKV-model).
3132
* Supports softprompts.
3233
* [Supports extensions](https://github.com/oobabooga/text-generation-webui/wiki/Extensions).
@@ -53,7 +54,7 @@ The third line assumes that you have an NVIDIA GPU.
5354
pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/rocm5.2
5455
```
5556

56-
* If you are running in CPU mode, replace the third command with this one:
57+
* If you are running it in CPU mode, replace the third command with this one:
5758

5859
```
5960
conda install pytorch torchvision torchaudio git -c pytorch
@@ -137,6 +138,8 @@ Optionally, you can use the following command-line flags:
137138
| `--cai-chat` | Launch the web UI in chat mode with a style similar to Character.AI's. If the file `img_bot.png` or `img_bot.jpg` exists in the same folder as server.py, this image will be used as the bot's profile picture. Similarly, `img_me.png` or `img_me.jpg` will be used as your profile picture. |
138139
| `--cpu` | Use the CPU to generate text.|
139140
| `--load-in-8bit` | Load the model with 8-bit precision.|
141+
| `--load-in-4bit` | Load the model with 4-bit precision. Currently only works with LLaMA.|
142+
| `--gptq-bits GPTQ_BITS` | Load a pre-quantized model with specified precision. 2, 3, 4 and 8 (bit) are supported. Currently only works with LLaMA. |
140143
| `--bf16` | Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU. |
141144
| `--auto-devices` | Automatically split the model across the available GPU(s) and CPU.|
142145
| `--disk` | If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk. |
@@ -176,14 +179,10 @@ Check the [wiki](https://github.com/oobabooga/text-generation-webui/wiki/System-
176179

177180
Pull requests, suggestions, and issue reports are welcome.
178181

179-
Before reporting a bug, make sure that you have created a conda environment and installed the dependencies exactly as in the *Installation* section above.
182+
Before reporting a bug, make sure that you have:
180183

181-
These issues are known:
182-
183-
* 8-bit doesn't work properly on Windows or older GPUs.
184-
* DeepSpeed doesn't work properly on Windows.
185-
186-
For these two, please try commenting on an existing issue instead of creating a new one.
184+
1. Created a conda environment and installed the dependencies exactly as in the *Installation* section above.
185+
2. [Searched](https://github.com/oobabooga/text-generation-webui/issues) to see if an issue already exists for the issue you encountered.
187186

188187
## Credits
189188

download-model.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
python download-model.py facebook/opt-1.3b
66
77
'''
8+
89
import argparse
10+
import base64
911
import json
1012
import multiprocessing
1113
import re
@@ -93,23 +95,28 @@ def select_model_from_default_options():
9395
def get_download_links_from_huggingface(model, branch):
9496
base = "https://huggingface.co"
9597
page = f"/api/models/{model}/tree/{branch}?cursor="
98+
cursor = b""
9699

97100
links = []
98101
classifications = []
99102
has_pytorch = False
100103
has_safetensors = False
101-
while page is not None:
102-
content = requests.get(f"{base}{page}").content
104+
while True:
105+
content = requests.get(f"{base}{page}{cursor.decode()}").content
106+
103107
dict = json.loads(content)
108+
if len(dict) == 0:
109+
break
104110

105111
for i in range(len(dict)):
106112
fname = dict[i]['path']
107113

108114
is_pytorch = re.match("pytorch_model.*\.bin", fname)
109115
is_safetensors = re.match("model.*\.safetensors", fname)
110-
is_text = re.match(".*\.(txt|json)", fname)
116+
is_tokenizer = re.match("tokenizer.*\.model", fname)
117+
is_text = re.match(".*\.(txt|json)", fname) or is_tokenizer
111118

112-
if is_text or is_safetensors or is_pytorch:
119+
if any((is_pytorch, is_safetensors, is_text, is_tokenizer)):
113120
if is_text:
114121
links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
115122
classifications.append('text')
@@ -123,8 +130,9 @@ def get_download_links_from_huggingface(model, branch):
123130
has_pytorch = True
124131
classifications.append('pytorch')
125132

126-
#page = dict['nextUrl']
127-
page = None
133+
cursor = base64.b64encode(f'{{"file_name":"{dict[-1]["path"]}"}}'.encode()) + b':50'
134+
cursor = base64.b64encode(cursor)
135+
cursor = cursor.replace(b'=', b'%3D')
128136

129137
# If both pytorch and safetensors are available, download safetensors only
130138
if has_pytorch and has_safetensors:

extensions/llama_prompts/script.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import gradio as gr
2+
import modules.shared as shared
3+
import pandas as pd
4+
5+
df = pd.read_csv("https://raw.githubusercontent.com/devbrones/llama-prompts/main/prompts/prompts.csv")
6+
7+
def get_prompt_by_name(name):
8+
if name == 'None':
9+
return ''
10+
else:
11+
return df[df['Prompt name'] == name].iloc[0]['Prompt'].replace('\\n', '\n')
12+
13+
def ui():
14+
if not shared.args.chat or shared.args.cai_chat:
15+
choices = ['None'] + list(df['Prompt name'])
16+
17+
prompts_menu = gr.Dropdown(value=choices[0], choices=choices, label='Prompt')
18+
prompts_menu.change(get_prompt_by_name, prompts_menu, shared.gradio['textbox'])

extensions/silero_tts/script.py

Lines changed: 121 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,45 @@
1+
import re
2+
import time
13
from pathlib import Path
24

35
import gradio as gr
46
import torch
57

8+
import modules.chat as chat
9+
import modules.shared as shared
10+
611
torch._C._jit_set_profiling_mode(False)
712

813
params = {
914
'activate': True,
10-
'speaker': 'en_56',
15+
'speaker': 'en_5',
1116
'language': 'en',
1217
'model_id': 'v3_en',
1318
'sample_rate': 48000,
1419
'device': 'cpu',
20+
'show_text': False,
21+
'autoplay': True,
22+
'voice_pitch': 'medium',
23+
'voice_speed': 'medium',
1524
}
25+
1626
current_params = params.copy()
1727
voices_by_gender = ['en_99', 'en_45', 'en_18', 'en_117', 'en_49', 'en_51', 'en_68', 'en_0', 'en_26', 'en_56', 'en_74', 'en_5', 'en_38', 'en_53', 'en_21', 'en_37', 'en_107', 'en_10', 'en_82', 'en_16', 'en_41', 'en_12', 'en_67', 'en_61', 'en_14', 'en_11', 'en_39', 'en_52', 'en_24', 'en_97', 'en_28', 'en_72', 'en_94', 'en_36', 'en_4', 'en_43', 'en_88', 'en_25', 'en_65', 'en_6', 'en_44', 'en_75', 'en_91', 'en_60', 'en_109', 'en_85', 'en_101', 'en_108', 'en_50', 'en_96', 'en_64', 'en_92', 'en_76', 'en_33', 'en_116', 'en_48', 'en_98', 'en_86', 'en_62', 'en_54', 'en_95', 'en_55', 'en_111', 'en_3', 'en_83', 'en_8', 'en_47', 'en_59', 'en_1', 'en_2', 'en_7', 'en_9', 'en_13', 'en_15', 'en_17', 'en_19', 'en_20', 'en_22', 'en_23', 'en_27', 'en_29', 'en_30', 'en_31', 'en_32', 'en_34', 'en_35', 'en_40', 'en_42', 'en_46', 'en_57', 'en_58', 'en_63', 'en_66', 'en_69', 'en_70', 'en_71', 'en_73', 'en_77', 'en_78', 'en_79', 'en_80', 'en_81', 'en_84', 'en_87', 'en_89', 'en_90', 'en_93', 'en_100', 'en_102', 'en_103', 'en_104', 'en_105', 'en_106', 'en_110', 'en_112', 'en_113', 'en_114', 'en_115']
18-
wav_idx = 0
28+
voice_pitches = ['x-low', 'low', 'medium', 'high', 'x-high']
29+
voice_speeds = ['x-slow', 'slow', 'medium', 'fast', 'x-fast']
30+
last_msg_id = 0
31+
32+
# Used for making text xml compatible, needed for voice pitch and speed control
33+
table = str.maketrans({
34+
"<": "&lt;",
35+
">": "&gt;",
36+
"&": "&amp;",
37+
"'": "&apos;",
38+
'"': "&quot;",
39+
})
40+
41+
def xmlesc(txt):
42+
return txt.translate(table)
1943

2044
def load_model():
2145
model, example_text = torch.hub.load(repo_or_dir='snakers4/silero-models', model='silero_tts', language=params['language'], speaker=params['model_id'])
@@ -33,20 +57,67 @@ def remove_surrounded_chars(string):
3357
new_string += char
3458
return new_string
3559

60+
def remove_tts_from_history():
61+
suffix = '_pygmalion' if 'pygmalion' in shared.model_name.lower() else ''
62+
for i, entry in enumerate(shared.history['internal']):
63+
reply = entry[1]
64+
reply = re.sub("(<USER>|<user>|{{user}})", shared.settings[f'name1{suffix}'], reply)
65+
if shared.args.chat:
66+
reply = reply.replace('\n', '<br>')
67+
shared.history['visible'][i][1] = reply
68+
69+
if shared.args.cai_chat:
70+
return chat.generate_chat_html(shared.history['visible'], shared.settings[f'name1{suffix}'], shared.settings[f'name1{suffix}'], shared.character)
71+
else:
72+
return shared.history['visible']
73+
74+
def toggle_text_in_history():
75+
suffix = '_pygmalion' if 'pygmalion' in shared.model_name.lower() else ''
76+
audio_str='\n\n' # The '\n\n' used after </audio>
77+
if shared.args.chat:
78+
audio_str='<br><br>'
79+
80+
if params['show_text']==True:
81+
#for i, entry in enumerate(shared.history['internal']):
82+
for i, entry in enumerate(shared.history['visible']):
83+
vis_reply = entry[1]
84+
if vis_reply.startswith('<audio'):
85+
reply = shared.history['internal'][i][1]
86+
reply = re.sub("(<USER>|<user>|{{user}})", shared.settings[f'name1{suffix}'], reply)
87+
if shared.args.chat:
88+
reply = reply.replace('\n', '<br>')
89+
shared.history['visible'][i][1] = vis_reply.split(audio_str,1)[0]+audio_str+reply
90+
else:
91+
for i, entry in enumerate(shared.history['visible']):
92+
vis_reply = entry[1]
93+
if vis_reply.startswith('<audio'):
94+
shared.history['visible'][i][1] = vis_reply.split(audio_str,1)[0]+audio_str
95+
96+
if shared.args.cai_chat:
97+
return chat.generate_chat_html(shared.history['visible'], shared.settings[f'name1{suffix}'], shared.settings[f'name1{suffix}'], shared.character)
98+
else:
99+
return shared.history['visible']
100+
36101
def input_modifier(string):
37102
"""
38103
This function is applied to your text inputs before
39104
they are fed into the model.
40105
"""
41106

107+
# Remove autoplay from previous chat history
108+
if (shared.args.chat or shared.args.cai_chat)and len(shared.history['internal'])>0:
109+
[visible_text, visible_reply] = shared.history['visible'][-1]
110+
vis_rep_clean = visible_reply.replace('controls autoplay>','controls>')
111+
shared.history['visible'][-1] = [visible_text, vis_rep_clean]
112+
42113
return string
43114

44115
def output_modifier(string):
45116
"""
46117
This function is applied to the model outputs.
47118
"""
48119

49-
global wav_idx, model, current_params
120+
global model, current_params
50121

51122
for i in params:
52123
if params[i] != current_params[i]:
@@ -57,20 +128,34 @@ def output_modifier(string):
57128
if params['activate'] == False:
58129
return string
59130

131+
orig_string = string
60132
string = remove_surrounded_chars(string)
61133
string = string.replace('"', '')
62134
string = string.replace('“', '')
63135
string = string.replace('\n', ' ')
64136
string = string.strip()
65137

138+
silent_string = False # Used to prevent unnecessary audio file generation
66139
if string == '':
67140
string = 'empty reply, try regenerating'
141+
silent_string = True
142+
143+
pitch = params['voice_pitch']
144+
speed = params['voice_speed']
145+
prosody=f'<prosody rate="{speed}" pitch="{pitch}">'
146+
string = '<speak>'+prosody+xmlesc(string)+'</prosody></speak>'
68147

69-
output_file = Path(f'extensions/silero_tts/outputs/{wav_idx:06d}.wav')
70-
model.save_wav(text=string, speaker=params['speaker'], sample_rate=int(params['sample_rate']), audio_path=str(output_file))
148+
if not shared.still_streaming and not silent_string:
149+
output_file = Path(f'extensions/silero_tts/outputs/{shared.character}_{int(time.time())}.wav')
150+
model.save_wav(ssml_text=string, speaker=params['speaker'], sample_rate=int(params['sample_rate']), audio_path=str(output_file))
151+
autoplay_str = ' autoplay' if params['autoplay'] else ''
152+
string = f'<audio src="file/{output_file.as_posix()}" controls{autoplay_str}></audio>\n\n'
153+
else:
154+
# Placeholder so text doesn't shift around so much
155+
string = '<audio controls></audio>\n\n'
71156

72-
string = f'<audio src="file/{output_file.as_posix()}" controls></audio>'
73-
wav_idx += 1
157+
if params['show_text']:
158+
string += orig_string
74159

75160
return string
76161

@@ -85,9 +170,36 @@ def bot_prefix_modifier(string):
85170

86171
def ui():
87172
# Gradio elements
88-
activate = gr.Checkbox(value=params['activate'], label='Activate TTS')
89-
voice = gr.Dropdown(value=params['speaker'], choices=voices_by_gender, label='TTS voice')
173+
with gr.Accordion("Silero TTS"):
174+
with gr.Row():
175+
activate = gr.Checkbox(value=params['activate'], label='Activate TTS')
176+
autoplay = gr.Checkbox(value=params['autoplay'], label='Play TTS automatically')
177+
show_text = gr.Checkbox(value=params['show_text'], label='Show message text under audio player')
178+
voice = gr.Dropdown(value=params['speaker'], choices=voices_by_gender, label='TTS voice')
179+
with gr.Row():
180+
v_pitch = gr.Dropdown(value=params['voice_pitch'], choices=voice_pitches, label='Voice pitch')
181+
v_speed = gr.Dropdown(value=params['voice_speed'], choices=voice_speeds, label='Voice speed')
182+
with gr.Row():
183+
convert = gr.Button('Permanently replace chat history audio with message text')
184+
convert_confirm = gr.Button('Confirm (cannot be undone)', variant="stop", visible=False)
185+
convert_cancel = gr.Button('Cancel', visible=False)
186+
187+
# Convert history with confirmation
188+
convert_arr = [convert_confirm, convert, convert_cancel]
189+
convert.click(lambda :[gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)], None, convert_arr)
190+
convert_confirm.click(lambda :[gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, convert_arr)
191+
convert_confirm.click(remove_tts_from_history, [], shared.gradio['display'])
192+
convert_confirm.click(lambda : chat.save_history(timestamp=False), [], [], show_progress=False)
193+
convert_cancel.click(lambda :[gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, convert_arr)
194+
195+
# Toggle message text in history
196+
show_text.change(lambda x: params.update({"show_text": x}), show_text, None)
197+
show_text.change(toggle_text_in_history, [], shared.gradio['display'])
198+
show_text.change(lambda : chat.save_history(timestamp=False), [], [], show_progress=False)
90199

91200
# Event functions to update the parameters in the backend
92201
activate.change(lambda x: params.update({"activate": x}), activate, None)
202+
autoplay.change(lambda x: params.update({"autoplay": x}), autoplay, None)
93203
voice.change(lambda x: params.update({"speaker": x}), voice, None)
204+
v_pitch.change(lambda x: params.update({"voice_pitch": x}), v_pitch, None)
205+
v_speed.change(lambda x: params.update({"voice_speed": x}), v_speed, None)

modules/RWKV.py

Lines changed: 6 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import os
22
from pathlib import Path
3-
from queue import Queue
4-
from threading import Thread
53

64
import numpy as np
75
from tokenizers import Tokenizer
86

97
import modules.shared as shared
8+
from modules.callbacks import Iteratorize
109

1110
np.set_printoptions(precision=4, suppress=True, linewidth=200)
1211

@@ -49,11 +48,11 @@ def generate(self, context="", token_count=20, temperature=1, top_p=1, top_k=50,
4948
return context+self.pipeline.generate(context, token_count=token_count, args=args, callback=callback)
5049

5150
def generate_with_streaming(self, **kwargs):
52-
iterable = Iteratorize(self.generate, kwargs, callback=None)
53-
reply = kwargs['context']
54-
for token in iterable:
55-
reply += token
56-
yield reply
51+
with Iteratorize(self.generate, kwargs, callback=None) as generator:
52+
reply = kwargs['context']
53+
for token in generator:
54+
reply += token
55+
yield reply
5756

5857
class RWKVTokenizer:
5958
def __init__(self):
@@ -73,38 +72,3 @@ def encode(self, prompt):
7372

7473
def decode(self, ids):
7574
return self.tokenizer.decode(ids)
76-
77-
class Iteratorize:
78-
79-
"""
80-
Transforms a function that takes a callback
81-
into a lazy iterator (generator).
82-
"""
83-
84-
def __init__(self, func, kwargs={}, callback=None):
85-
self.mfunc=func
86-
self.c_callback=callback
87-
self.q = Queue(maxsize=1)
88-
self.sentinel = object()
89-
self.kwargs = kwargs
90-
91-
def _callback(val):
92-
self.q.put(val)
93-
94-
def gentask():
95-
ret = self.mfunc(callback=_callback, **self.kwargs)
96-
self.q.put(self.sentinel)
97-
if self.c_callback:
98-
self.c_callback(ret)
99-
100-
Thread(target=gentask).start()
101-
102-
def __iter__(self):
103-
return self
104-
105-
def __next__(self):
106-
obj = self.q.get(True,None)
107-
if obj is self.sentinel:
108-
raise StopIteration
109-
else:
110-
return obj

0 commit comments

Comments
 (0)