VanYsa commited on
Commit
c69c60b
·
1 Parent(s): 19df411

testing meta pure

Browse files
Files changed (1) hide show
  1. app.py +71 -176
app.py CHANGED
@@ -1,17 +1,6 @@
1
  import gradio as gr
2
- import json
3
- import librosa
4
  import os
5
- import soundfile as sf
6
- import tempfile
7
- import uuid
8
- import transformers
9
- import torch
10
- import time
11
  import spaces
12
-
13
- from nemo.collections.asr.models import ASRModel
14
-
15
  from transformers import GemmaTokenizer, AutoModelForCausalLM
16
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
17
  from threading import Thread
@@ -20,132 +9,53 @@ from threading import Thread
20
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
21
 
22
 
23
- SAMPLE_RATE = 16000 # Hz
24
- MAX_AUDIO_SECONDS = 40 # wont try to transcribe if longer than this
25
  DESCRIPTION = '''
26
  <div>
27
- <h1 style='text-align: center'>MyAlexa: Voice Chat Assistant</h1>
28
- <p style='text-align: center'>MyAlexa is a demo of a voice chat assistant with chat logs that accepts audio input and outputs an AI response. </p>
29
- <p>This space uses <a href="https://huggingface.co/nvidia/canary-1b"><b>NVIDIA Canary 1B</b></a> for Automatic Speech-to-text Recognition (ASR), <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct"><b>Meta Llama 3 8B Insruct</b></a> for the large language model (LLM) and <a href="https://https://huggingface.co/docs/transformers/en/model_doc/vits"><b>VITS</b></a> for text to speech (TTS).</p>
30
- <p>This demo accepts audio inputs not more than 40 seconds long.</p>
31
- <p>Transcription and responses are limited to the English language.</p>
32
  </div>
33
  '''
 
 
 
 
 
 
 
34
  PLACEHOLDER = """
35
  <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
36
- <img src="https://i.ibb.co/S35q17Q/My-Alexa-Logo.png" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
37
- <p style="font-size: 28px; margin-bottom: 2px; opacity: 0.65;">What's on your mind?</p>
 
38
  </div>
39
  """
40
 
41
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
42
 
43
- ### ASR model
44
- canary_model = ASRModel.from_pretrained("nvidia/canary-1b").to(device)
45
- canary_model.eval()
46
-
47
- # make sure beam size always 1 for consistency
48
- canary_model.change_decoding_strategy(None)
49
- decoding_cfg = canary_model.cfg.decoding
50
- decoding_cfg.beam.beam_size = 1
51
- canary_model.change_decoding_strategy(decoding_cfg)
 
 
 
52
 
53
- ### LLM model
54
  # Load the tokenizer and model
55
  tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
56
- llama3_model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto") # to("cuda:0")
57
  terminators = [
58
  tokenizer.eos_token_id,
59
  tokenizer.convert_tokens_to_ids("<|eot_id|>")
60
  ]
61
 
62
- def convert_audio(audio_filepath, tmpdir, utt_id):
63
- """
64
- Convert all files to monochannel 16 kHz wav files.
65
- Do not convert and raise error if audio is too long.
66
- Returns output filename and duration.
67
- """
68
-
69
- data, sr = librosa.load(audio_filepath, sr=None, mono=True)
70
-
71
- duration = librosa.get_duration(y=data, sr=sr)
72
-
73
- if duration > MAX_AUDIO_SECONDS:
74
- raise gr.Error(
75
- f"This demo can transcribe up to {MAX_AUDIO_SECONDS} seconds of audio. "
76
- "If you wish, you may trim the audio using the Audio viewer in Step 1 "
77
- "(click on the scissors icon to start trimming audio)."
78
- )
79
-
80
- if sr != SAMPLE_RATE:
81
- data = librosa.resample(data, orig_sr=sr, target_sr=SAMPLE_RATE)
82
-
83
- out_filename = os.path.join(tmpdir, utt_id + '.wav')
84
-
85
- # save output audio
86
- sf.write(out_filename, data, SAMPLE_RATE)
87
-
88
- return out_filename, duration
89
-
90
- def transcribe(audio_filepath):
91
- """
92
- Transcribes a converted audio file.
93
- Set to english language with punctuations.
94
- Returns the output text.
95
- """
96
-
97
- if audio_filepath is None:
98
- raise gr.Error("Please provide some input audio: either upload an audio file or use the microphone")
99
-
100
- utt_id = uuid.uuid4()
101
- with tempfile.TemporaryDirectory() as tmpdir:
102
- converted_audio_filepath, duration = convert_audio(audio_filepath, tmpdir, str(utt_id))
103
-
104
- # make manifest file and save
105
- manifest_data = {
106
- "audio_filepath": converted_audio_filepath,
107
- "source_lang": "en",
108
- "target_lang": "en",
109
- "taskname": "asr",
110
- "pnc": "yes",
111
- "answer": "predict",
112
- "duration": str(duration),
113
- }
114
-
115
- manifest_filepath = os.path.join(tmpdir, f'{utt_id}.json')
116
-
117
- with open(manifest_filepath, 'w') as fout:
118
- line = json.dumps(manifest_data)
119
- fout.write(line + '\n')
120
-
121
- # call transcribe, passing in manifest filepath
122
- output_text = canary_model.transcribe(manifest_filepath)[0]
123
-
124
- return output_text
125
-
126
- def add_message(history, message):
127
- """
128
- Adds the input message in the chatbot.
129
- Returns the updated chatbot with an empty input textbox.
130
- """
131
- history.append((message, None))
132
- return history
133
-
134
- def bot(history,message):
135
- """
136
- Prints the LLM's response in the chatbot
137
- """
138
- response = bot_response(message, history, 0.7, 100)
139
- #response = "bot_response(message)"
140
- history[-1][1] = ""
141
- for character in response:
142
- history[-1][1] += character
143
- time.sleep(0.05)
144
- yield history
145
-
146
-
147
- @spaces.GPU()
148
- def bot_response(message: str,
149
  history: list,
150
  temperature: float,
151
  max_new_tokens: int
@@ -165,7 +75,7 @@ def bot_response(message: str,
165
  conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
166
  conversation.append({"role": "user", "content": message})
167
 
168
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(llama3_model.device)
169
 
170
  streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
171
 
@@ -181,68 +91,53 @@ def bot_response(message: str,
181
  if temperature == 0:
182
  generate_kwargs['do_sample'] = False
183
 
184
- t = Thread(target=llama3_model.generate, kwargs=generate_kwargs)
185
  t.start()
186
 
187
  outputs = []
188
  for text in streamer:
189
  outputs.append(text)
 
 
 
190
 
191
- return "".join(outputs)
192
-
193
-
194
- with gr.Blocks(
195
- title="MyAlexa",
196
- css="""
197
- textarea { font-size: 18px;}
198
- """,
199
- theme=gr.themes.Default(text_size=gr.themes.sizes.text_lg) # make text slightly bigger (default is text_md )
200
- ) as demo:
201
-
202
- gr.HTML(DESCRIPTION)
203
- chatbot = gr.Chatbot(
204
- [],
205
- elem_id="chatbot",
206
- bubble_full_width=False,
207
- placeholder=PLACEHOLDER,
208
- label='MyAlexa'
209
- )
210
- with gr.Row():
211
- with gr.Column():
212
- gr.HTML(
213
- "<p><b>Step 1:</b> Upload an audio file or record with your microphone.</p>"
214
- )
215
-
216
- audio_file = gr.Audio(sources=["microphone", "upload"], type="filepath")
217
-
218
-
219
- with gr.Column():
220
-
221
- gr.HTML("<p><b>Step 2:</b> Enter audio as input and wait for MyAlexa's response.</p>")
222
-
223
- submit_button = gr.Button(
224
- value="Submit audio",
225
- variant="primary"
226
- )
227
-
228
- chat_input = gr.Textbox(
229
- label="Transcribed text:",
230
- interactive=False,
231
- placeholder="Enter message",
232
- elem_id="chat_input",
233
- visible=True
234
- )
235
-
236
- chat_msg = chat_input.change(add_message, [chatbot, chat_input], [chatbot])
237
- bot_msg = chat_msg.then(bot, [chatbot, chat_input], chatbot, api_name="bot_response")
238
- # bot_msg.then(lambda: gr.Textbox(interactive=False), None, [chat_input])
239
-
240
- submit_button.click(
241
- fn=transcribe,
242
- inputs = [audio_file],
243
- outputs = [chat_input]
244
- )
245
 
246
- demo.queue()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  if __name__ == "__main__":
248
  demo.launch()
 
1
  import gradio as gr
 
 
2
  import os
 
 
 
 
 
 
3
  import spaces
 
 
 
4
  from transformers import GemmaTokenizer, AutoModelForCausalLM
5
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
  from threading import Thread
 
9
  HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
 
11
 
 
 
12
  DESCRIPTION = '''
13
  <div>
14
+ <h1 style="text-align: center;">Meta Llama3 8B</h1>
15
+ <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct"><b>Meta Llama3 8b Chat</b></a>. Meta Llama3 is the new open LLM and comes in two sizes: 8b and 70b. Feel free to play with it, or duplicate to run privately!</p>
16
+ <p>🔎 For more details about the Llama3 release and how to use the model with <code>transformers</code>, take a look <a href="https://huggingface.co/blog/llama3">at our blog post</a>.</p>
17
+ <p>🦕 Looking for an even more powerful model? Check out the <a href="https://huggingface.co/chat/"><b>Hugging Chat</b></a> integration for Meta Llama 3 70b</p>
 
18
  </div>
19
  '''
20
+
21
+ LICENSE = """
22
+ <p/>
23
+ ---
24
+ Built with Meta Llama 3
25
+ """
26
+
27
  PLACEHOLDER = """
28
  <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
29
+ <img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/8e75e61cc9bab22b7ce3dec85ab0e6db1da5d107/Meta_lockup_positive%20primary_RGB.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
30
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3</h1>
31
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
32
  </div>
33
  """
34
 
 
35
 
36
+ css = """
37
+ h1 {
38
+ text-align: center;
39
+ display: block;
40
+ }
41
+ #duplicate-button {
42
+ margin: auto;
43
+ color: white;
44
+ background: #1565c0;
45
+ border-radius: 100vh;
46
+ }
47
+ """
48
 
 
49
  # Load the tokenizer and model
50
  tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
51
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto") # to("cuda:0")
52
  terminators = [
53
  tokenizer.eos_token_id,
54
  tokenizer.convert_tokens_to_ids("<|eot_id|>")
55
  ]
56
 
57
+ @spaces.GPU(duration=120)
58
+ def chat_llama3_8b(message: str,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  history: list,
60
  temperature: float,
61
  max_new_tokens: int
 
75
  conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
76
  conversation.append({"role": "user", "content": message})
77
 
78
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
79
 
80
  streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
81
 
 
91
  if temperature == 0:
92
  generate_kwargs['do_sample'] = False
93
 
94
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
95
  t.start()
96
 
97
  outputs = []
98
  for text in streamer:
99
  outputs.append(text)
100
+ #print(outputs)
101
+ yield "".join(outputs)
102
+
103
 
104
+ # Gradio block
105
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ with gr.Blocks(fill_height=True, css=css) as demo:
108
+
109
+ gr.Markdown(DESCRIPTION)
110
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
111
+ gr.ChatInterface(
112
+ fn=chat_llama3_8b,
113
+ chatbot=chatbot,
114
+ fill_height=True,
115
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
116
+ additional_inputs=[
117
+ gr.Slider(minimum=0,
118
+ maximum=1,
119
+ step=0.1,
120
+ value=0.95,
121
+ label="Temperature",
122
+ render=False),
123
+ gr.Slider(minimum=128,
124
+ maximum=4096,
125
+ step=1,
126
+ value=512,
127
+ label="Max new tokens",
128
+ render=False ),
129
+ ],
130
+ examples=[
131
+ ['How to setup a human base on Mars? Give short answer.'],
132
+ ['Explain theory of relativity to me like I’m 8 years old.'],
133
+ ['What is 9,000 * 9,000?'],
134
+ ['Write a pun-filled happy birthday message to my friend Alex.'],
135
+ ['Justify why a penguin might make a good king of the jungle.']
136
+ ],
137
+ cache_examples=False,
138
+ )
139
+
140
+ gr.Markdown(LICENSE)
141
+
142
  if __name__ == "__main__":
143
  demo.launch()