File size: 10,556 Bytes
5a3dbe8 cba19c5 81e4a88 c1c886a 81e4a88 c1c886a 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 5a3dbe8 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 cba19c5 81e4a88 5a3dbe8 5e72a11 5a3dbe8 5e2a02e 5a3dbe8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
import streamlit as st
from faster_whisper import WhisperModel
import datetime
import subprocess
from pathlib import Path
import pandas as pd
import re
import time
import os
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
import torch
from pyannote.audio.pipelines.speaker_verification import PretrainedSpeakerEmbedding
from pyannote.audio import Audio
from pyannote.core import Segment
import wave
import contextlib
from transformers import pipeline
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer
import onnxruntime
import numpy as np
import librosa
whisper_models = ["tiny", "base", "small", "medium", "large-v1", "large-v2"]
source_languages = {"en": "English"}
MODEL_NAME = "vumichien/whisper-medium-jp"
lang = "en"
device = 0 if torch.cuda.is_available() else "cpu"
embedding_model = PretrainedSpeakerEmbedding(
"speechbrain/spkrec-ecapa-voxceleb",
device=torch.device("cuda"))
#LLAMA prep
# from huggingface_hub import login
# login("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")
# import torch
# import transformers
# from transformers import AutoTokenizer, AutoModelForCausalLM
# from langchain import HuggingFacePipeline
# from langchain import PromptTemplate, LLMChain
# tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf",
# use_auth_token=True,)
# model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf",
# device_map='auto',
# torch_dtype=torch.float16,
# use_auth_token=True,
# # load_in_8bit=True,
# # load_in_4bit=True
# )
# # Use a pipeline for later
# from transformers import pipeline
# pipe = pipeline("text-generation",
# model=model,
# tokenizer= tokenizer,
# torch_dtype=torch.bfloat16,
# device_map="auto",
# max_new_tokens = 512,
# do_sample=True,
# top_k=30,
# num_return_sequences=1,
# eos_token_id=tokenizer.eos_token_id
# )
# import json
# import textwrap
# B_INST, E_INST = "[INST]", "[/INST]"
# B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
# DEFAULT_SYSTEM_PROMPT = """\
# You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
# If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."""
# def get_prompt(instruction, new_system_prompt=DEFAULT_SYSTEM_PROMPT ):
# SYSTEM_PROMPT = B_SYS + new_system_prompt + E_SYS
# prompt_template = B_INST + SYSTEM_PROMPT + instruction + E_INST
# return prompt_template
# def cut_off_text(text, prompt):
# cutoff_phrase = prompt
# index = text.find(cutoff_phrase)
# if index != -1:
# return text[:index]
# else:
# return text
# def remove_substring(string, substring):
# return string.replace(substring, "")
# def generate(text):
# prompt = get_prompt(text)
# with torch.autocast('cuda', dtype=torch.bfloat16):
# inputs = tokenizer(prompt, return_tensors="pt").to('cuda')
# outputs = model.generate(**inputs,
# max_new_tokens=512,
# eos_token_id=tokenizer.eos_token_id,
# pad_token_id=tokenizer.eos_token_id,
# )
# final_outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
# final_outputs = cut_off_text(final_outputs, '</s>')
# final_outputs = remove_substring(final_outputs, prompt)
# return final_outputs#, outputs
# def parse_text(text):
# wrapped_text = textwrap.fill(text, width=100)
# print(wrapped_text +'\n\n')
# # return assistant_text
# llm = HuggingFacePipeline(pipeline = pipe, model_kwargs = {'temperature':0})
def segment_embedding(segment, duration, audio_file):
audio = Audio()
start = segment["start"]
# Whisper overshoots the end timestamp in the last segment
end = min(duration, segment["end"])
clip = Segment(start, end)
waveform, sample_rate = audio.crop(audio_file, clip)
return embedding_model(waveform[None])
def fast_whisper(audio_file, model):
# Transcribe audio
options = dict(language=lang, beam_size=5, best_of=5)
transcribe_options = dict(task="transcribe", **options)
segments_raw, info = model.transcribe(audio_file, **transcribe_options)
# Convert back to original openai format
segments = []
i = 0
for segment_chunk in segments_raw:
chunk = {}
chunk["start"] = segment_chunk.start
chunk["end"] = segment_chunk.end
chunk["text"] = segment_chunk.text
segments.append(chunk)
i += 1
print("transcribe audio done with fast whisper")
return segments
def get_embeddings(segments, duration, audio_file):
embeddings = np.zeros(shape=(len(segments), 192))
for i, segment in enumerate(segments):
embeddings[i] = segment_embedding(segment, duration, audio_file)
embeddings = np.nan_to_num(embeddings)
print("Got embeddings for segments")
return embeddings
def get_n_speakers(embeddings, num_speakers):
if num_speakers == 0:
# Find the best number of speakers
score_num_speakers = {}
for num_speakers in range(2, 10+1):
clustering = AgglomerativeClustering(num_speakers).fit(embeddings)
score = silhouette_score(embeddings, clustering.labels_, metric='euclidean')
score_num_speakers[num_speakers] = score
best_num_speaker = max(score_num_speakers, key=lambda x:score_num_speakers[x])
print(f"The best number of speakers: {best_num_speaker} with {score_num_speakers[best_num_speaker]} score")
else:
best_num_speaker = num_speakers
print(f"best num speakers is {best_num_speaker}")
return best_num_speaker
def assign_speaker(best_num_speaker, embeddings, segments):
# Assign speaker label
clustering = AgglomerativeClustering(best_num_speaker).fit(embeddings)
labels = clustering.labels_
for i in range(len(segments)):
segments[i]["speaker"] = 'SPEAKER ' + str(labels[i] + 1)
print(f"I know who said what now")
return segments
def convert_time(secs):
return datetime.timedelta(seconds=round(secs))
def segments2df(segments):
# Make output
objects = {
'Start' : [],
'End': [],
'Speaker': [],
'Text': []
}
text = ''
for (i, segment) in enumerate(segments):
if i == 0 or segments[i - 1]["speaker"] != segment["speaker"]:
objects['Start'].append(str(convert_time(segment["start"])))
objects['Speaker'].append(segment["speaker"])
if i != 0:
objects['End'].append(str(convert_time(segments[i - 1]["end"])))
objects['Text'].append(text)
text = ''
text += segment["text"] + ' '
objects['End'].append(str(convert_time(segments[i - 1]["end"])))
objects['Text'].append(text)
df_results = pd.DataFrame(objects)
return df_results
def speech_to_text(audio_file, whisper_model, num_speakers=0):
model = WhisperModel(whisper_model, compute_type="int8")
time_start = time.time()
if(audio_file == None): raise ValueError("Error no audio_file")
model = WhisperModel(whisper_model, compute_type="int8")
y, sr = librosa.load(audio_file)
duration = len(y)/sr
segments = fast_whisper(audio_file, model)
embeddings = get_embeddings(segments, duration, audio_file)
best_num_speaker = get_n_speakers(embeddings, num_speakers)
segments = assign_speaker(best_num_speaker, embeddings, segments)
diary = segments2df(segments)
return diary
onnx_path = hf_hub_download(repo_id='UKP-SQuARE/roberta-base-pf-boolq-onnx', filename='model.onnx') # or model_quant.onnx for quantization
onnx_model = onnxruntime.InferenceSession(onnx_path, providers=['CPUExecutionProvider'])
question = 'Can she answer'
tokenizer = AutoTokenizer.from_pretrained('UKP-SQuARE/roberta-base-pf-boolq-onnx')
def answer(context, question):
# inputs = tokenizer(question, context, padding=True, truncation=True, return_tensors='np')
# inputs = {key: np.array(inputs[key], dtype=np.int64) for key in inputs}
# outputs = onnx_model.run(input_feed=dict(inputs), output_names=None)
# instruction = f"conversation: '''{context}'''"+"\n based on the provided conversation in triple quotes answer next question.\n Question: {text}"
# system_prompt = "You are an expert and answer any question based on conversation. You analys the conversation in light of the question then you answer with yes, no or not clear only. You only output one or two words"
# template = get_prompt(instruction, system_prompt)
# print(template)
# prompt = PromptTemplate(template=template, input_variables=["text"])
# llm_chain = LLMChain(prompt=prompt, llm=llm)
# output = llm_chain.run(question)
# return parse_text(output)
return "please use the other app"
uploaded_file = st.sidebar.file_uploader("Choose a file")
num_speakers = st.sidebar.slider("num speakers (0 means auto detect)", 0, 10, 0)
diary = None
question = None
if uploaded_file is not None:
filename = uploaded_file.name
with open(filename, "wb") as f:
f.write(uploaded_file.getbuffer())
# st.write(os.listdir("./"))
if st.sidebar.checkbox('Get conversation'):
torch.cuda.empty_cache()
whisper_model = "base"
diary = speech_to_text(filename, whisper_model, num_speakers=num_speakers)
st.dataframe(diary.style.highlight_max(axis=0))
question = st.sidebar.text_input('Question', 'Can she answer')
if st.sidebar.button('Answer'):
diary["text_all"] = diary["Speaker"] + ": "+ diary["Text"]
context = " \n ".join(diary["text_all"].to_list())
outputs = answer(context, question)
outputs = outputs[0][0]
if outputs[0]>outputs[1]: st.sidebar.write("Answer is Yes")
if outputs[0]<outputs[1]: st.sidebar.write("Answer is No")
|