Spaces:
Runtime error
Runtime error
Arnaudding001
commited on
Commit
•
606aeb0
1
Parent(s):
b1004b6
Create cli.py
Browse files
cli.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import pathlib
|
4 |
+
from urllib.parse import urlparse
|
5 |
+
import warnings
|
6 |
+
import numpy as np
|
7 |
+
|
8 |
+
import whisper
|
9 |
+
|
10 |
+
import torch
|
11 |
+
from app import LANGUAGES, WhisperTranscriber
|
12 |
+
from src.download import download_url
|
13 |
+
|
14 |
+
from src.utils import optional_float, optional_int, str2bool
|
15 |
+
|
16 |
+
|
17 |
+
def cli():
|
18 |
+
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
19 |
+
parser.add_argument("audio", nargs="+", type=str, help="audio file(s) to transcribe")
|
20 |
+
parser.add_argument("--model", default="small", choices=["tiny", "base", "small", "medium", "large"], help="name of the Whisper model to use")
|
21 |
+
parser.add_argument("--model_dir", type=str, default=None, help="the path to save model files; uses ~/.cache/whisper by default")
|
22 |
+
parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu", help="device to use for PyTorch inference")
|
23 |
+
parser.add_argument("--output_dir", "-o", type=str, default=".", help="directory to save the outputs")
|
24 |
+
parser.add_argument("--verbose", type=str2bool, default=True, help="whether to print out the progress and debug messages")
|
25 |
+
|
26 |
+
parser.add_argument("--task", type=str, default="transcribe", choices=["transcribe", "translate"], help="whether to perform X->X speech recognition ('transcribe') or X->English translation ('translate')")
|
27 |
+
parser.add_argument("--language", type=str, default=None, choices=sorted(LANGUAGES), help="language spoken in the audio, specify None to perform language detection")
|
28 |
+
|
29 |
+
parser.add_argument("--vad", type=str, default="none", choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], help="The voice activity detection algorithm to use")
|
30 |
+
parser.add_argument("--vad_merge_window", type=optional_float, default=5, help="The window size (in seconds) to merge voice segments")
|
31 |
+
parser.add_argument("--vad_max_merge_size", type=optional_float, default=30, help="The maximum size (in seconds) of a voice segment")
|
32 |
+
parser.add_argument("--vad_padding", type=optional_float, default=1, help="The padding (in seconds) to add to each voice segment")
|
33 |
+
parser.add_argument("--vad_prompt_window", type=optional_float, default=3, help="The window size of the prompt to pass to Whisper")
|
34 |
+
|
35 |
+
parser.add_argument("--temperature", type=float, default=0, help="temperature to use for sampling")
|
36 |
+
parser.add_argument("--best_of", type=optional_int, default=5, help="number of candidates when sampling with non-zero temperature")
|
37 |
+
parser.add_argument("--beam_size", type=optional_int, default=5, help="number of beams in beam search, only applicable when temperature is zero")
|
38 |
+
parser.add_argument("--patience", type=float, default=None, help="optional patience value to use in beam decoding, as in https://arxiv.org/abs/2204.05424, the default (1.0) is equivalent to conventional beam search")
|
39 |
+
parser.add_argument("--length_penalty", type=float, default=None, help="optional token length penalty coefficient (alpha) as in https://arxiv.org/abs/1609.08144, uses simple lengt normalization by default")
|
40 |
+
|
41 |
+
parser.add_argument("--suppress_tokens", type=str, default="-1", help="comma-separated list of token ids to suppress during sampling; '-1' will suppress most special characters except common punctuations")
|
42 |
+
parser.add_argument("--initial_prompt", type=str, default=None, help="optional text to provide as a prompt for the first window.")
|
43 |
+
parser.add_argument("--condition_on_previous_text", type=str2bool, default=True, help="if True, provide the previous output of the model as a prompt for the next window; disabling may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop")
|
44 |
+
parser.add_argument("--fp16", type=str2bool, default=True, help="whether to perform inference in fp16; True by default")
|
45 |
+
|
46 |
+
parser.add_argument("--temperature_increment_on_fallback", type=optional_float, default=0.2, help="temperature to increase when falling back when the decoding fails to meet either of the thresholds below")
|
47 |
+
parser.add_argument("--compression_ratio_threshold", type=optional_float, default=2.4, help="if the gzip compression ratio is higher than this value, treat the decoding as failed")
|
48 |
+
parser.add_argument("--logprob_threshold", type=optional_float, default=-1.0, help="if the average log probability is lower than this value, treat the decoding as failed")
|
49 |
+
parser.add_argument("--no_speech_threshold", type=optional_float, default=0.6, help="if the probability of the <|nospeech|> token is higher than this value AND the decoding has failed due to `logprob_threshold`, consider the segment as silence")
|
50 |
+
|
51 |
+
args = parser.parse_args().__dict__
|
52 |
+
model_name: str = args.pop("model")
|
53 |
+
model_dir: str = args.pop("model_dir")
|
54 |
+
output_dir: str = args.pop("output_dir")
|
55 |
+
device: str = args.pop("device")
|
56 |
+
os.makedirs(output_dir, exist_ok=True)
|
57 |
+
|
58 |
+
if model_name.endswith(".en") and args["language"] not in {"en", "English"}:
|
59 |
+
warnings.warn(f"{model_name} is an English-only model but receipted '{args['language']}'; using English instead.")
|
60 |
+
args["language"] = "en"
|
61 |
+
|
62 |
+
temperature = args.pop("temperature")
|
63 |
+
temperature_increment_on_fallback = args.pop("temperature_increment_on_fallback")
|
64 |
+
if temperature_increment_on_fallback is not None:
|
65 |
+
temperature = tuple(np.arange(temperature, 1.0 + 1e-6, temperature_increment_on_fallback))
|
66 |
+
else:
|
67 |
+
temperature = [temperature]
|
68 |
+
|
69 |
+
vad = args.pop("vad")
|
70 |
+
vad_merge_window = args.pop("vad_merge_window")
|
71 |
+
vad_max_merge_size = args.pop("vad_max_merge_size")
|
72 |
+
vad_padding = args.pop("vad_padding")
|
73 |
+
vad_prompt_window = args.pop("vad_prompt_window")
|
74 |
+
|
75 |
+
model = whisper.load_model(model_name, device=device, download_root=model_dir)
|
76 |
+
transcriber = WhisperTranscriber(deleteUploadedFiles=False)
|
77 |
+
|
78 |
+
for audio_path in args.pop("audio"):
|
79 |
+
sources = []
|
80 |
+
|
81 |
+
# Detect URL and download the audio
|
82 |
+
if (uri_validator(audio_path)):
|
83 |
+
# Download from YouTube/URL directly
|
84 |
+
for source_path in download_url(audio_path, maxDuration=-1, destinationDirectory=output_dir, playlistItems=None):
|
85 |
+
source_name = os.path.basename(source_path)
|
86 |
+
sources.append({ "path": source_path, "name": source_name })
|
87 |
+
else:
|
88 |
+
sources.append({ "path": audio_path, "name": os.path.basename(audio_path) })
|
89 |
+
|
90 |
+
for source in sources:
|
91 |
+
source_path = source["path"]
|
92 |
+
source_name = source["name"]
|
93 |
+
|
94 |
+
result = transcriber.transcribe_file(model, source_path, temperature=temperature,
|
95 |
+
vad=vad, vadMergeWindow=vad_merge_window, vadMaxMergeSize=vad_max_merge_size,
|
96 |
+
vadPadding=vad_padding, vadPromptWindow=vad_prompt_window, **args)
|
97 |
+
|
98 |
+
transcriber.write_result(result, source_name, output_dir)
|
99 |
+
|
100 |
+
transcriber.clear_cache()
|
101 |
+
|
102 |
+
def uri_validator(x):
|
103 |
+
try:
|
104 |
+
result = urlparse(x)
|
105 |
+
return all([result.scheme, result.netloc])
|
106 |
+
except:
|
107 |
+
return False
|
108 |
+
|
109 |
+
if __name__ == '__main__':
|
110 |
+
cli()
|