JackismyShephard commited on
Commit
26ab82d
·
1 Parent(s): 6780507

add app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import pipeline
3
+ import gradio as gr
4
+
5
+ MODEL_NAME = "JackismyShephard/whisper-tiny-finetuned-minds14"
6
+ BATCH_SIZE = 8
7
+
8
+ device = 0 if torch.cuda.is_available() else "cpu"
9
+
10
+ pipe = pipeline(
11
+ task="automatic-speech-recognition",
12
+ model=MODEL_NAME,
13
+ chunk_length_s=30,
14
+ device=device,
15
+ )
16
+
17
+
18
+ # Copied from https://github.com/openai/whisper/blob/c09a7ae299c4c34c5839a76380ae407e7d785914/whisper/utils.py#L50
19
+ def format_timestamp(
20
+ seconds: float, always_include_hours: bool = False, decimal_marker: str = "."
21
+ ):
22
+ if seconds is not None:
23
+ milliseconds = round(seconds * 1000.0)
24
+
25
+ hours = milliseconds // 3_600_000
26
+ milliseconds -= hours * 3_600_000
27
+
28
+ minutes = milliseconds // 60_000
29
+ milliseconds -= minutes * 60_000
30
+
31
+ seconds = milliseconds // 1_000
32
+ milliseconds -= seconds * 1_000
33
+
34
+ hours_marker = f"{hours:02d}:" if always_include_hours or hours > 0 else ""
35
+ return f"{hours_marker}{minutes:02d}:{seconds:02d}{decimal_marker}{milliseconds:03d}"
36
+ else:
37
+ # we have a malformed timestamp so just return it as is
38
+ return seconds
39
+
40
+
41
+ def transcribe(file, task, return_timestamps):
42
+ outputs = pipe(
43
+ file,
44
+ batch_size=BATCH_SIZE,
45
+ generate_kwargs={
46
+ "task": task,
47
+ "language": "english",
48
+ },
49
+ return_timestamps=return_timestamps,
50
+ )
51
+ text = outputs["text"]
52
+ if return_timestamps:
53
+ timestamps = outputs["chunks"]
54
+ timestamps = [
55
+ f"[{format_timestamp(chunk['timestamp'][0])} -> {format_timestamp(chunk['timestamp'][1])}] {chunk['text']}"
56
+ for chunk in timestamps
57
+ ]
58
+ text = "\n".join(str(feature) for feature in timestamps)
59
+ return text
60
+
61
+
62
+ demo = gr.Interface(
63
+ fn=transcribe,
64
+ inputs=[
65
+ gr.Audio(label="Audio", type="filepath"),
66
+ gr.inputs.Radio(
67
+ ["transcribe", "translate"], label="Task", default="transcribe"
68
+ ),
69
+ gr.inputs.Checkbox(default=False, label="Return timestamps"),
70
+ ],
71
+ outputs=gr.Textbox(),
72
+ title="Automatic Speech Recognition",
73
+ description=(
74
+ "Transcribe or translate long-form microphone or audio inputs with the click of a button! Demo uses the"
75
+ f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe or translate audio files"
76
+ " of arbitrary length."
77
+ ),
78
+ examples="./examples",
79
+ cache_examples=True,
80
+ allow_flagging="never",
81
+ )
82
+
83
+ demo.launch()