asahi417 commited on
Commit
18fb4f3
β€’
1 Parent(s): 12682cf
Files changed (5) hide show
  1. .gitignore +1 -0
  2. README.md +6 -5
  3. app.py +110 -0
  4. packages.txt +1 -0
  5. requirements.txt +2 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .idea
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Kotoba Whisper Bilingual Demo
3
- emoji: πŸ“š
4
- colorFrom: green
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 4.44.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Kotoba Whisper Demo
3
+ emoji: πŸ”₯
4
+ colorFrom: yellow
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.39.0
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from math import floor
3
+ from typing import Optional
4
+
5
+ import spaces
6
+ import torch
7
+ import gradio as gr
8
+ from transformers import pipeline
9
+ from transformers.pipelines.audio_utils import ffmpeg_read
10
+
11
+
12
+ # configuration
13
+ MODEL_NAME = "japanese-asr/distil-whisper-bilingual-v1.0"
14
+ BATCH_SIZE = 16
15
+ CHUNK_LENGTH_S = 15
16
+ # device setting
17
+ if torch.cuda.is_available():
18
+ torch_dtype = torch.bfloat16
19
+ device = "cuda"
20
+ model_kwargs = {'attn_implementation': 'sdpa'}
21
+ else:
22
+ torch_dtype = torch.float32
23
+ device = "cpu"
24
+ model_kwargs = {}
25
+
26
+ # define the pipeline
27
+ pipe = pipeline(
28
+ model=MODEL_NAME,
29
+ chunk_length_s=CHUNK_LENGTH_S,
30
+ batch_size=BATCH_SIZE,
31
+ torch_dtype=torch_dtype,
32
+ device=device,
33
+ model_kwargs=model_kwargs,
34
+ trust_remote_code=True
35
+ )
36
+
37
+
38
+ def format_time(start: Optional[float], end: Optional[float]):
39
+
40
+ def _format_time(seconds: Optional[float]):
41
+ if seconds is None:
42
+ return "complete "
43
+ minutes = floor(seconds / 60)
44
+ hours = floor(seconds / 3600)
45
+ seconds = seconds - hours * 3600 - minutes * 60
46
+ m_seconds = floor(round(seconds - floor(seconds), 3) * 10 ** 3)
47
+ seconds = floor(seconds)
48
+ return f'{hours:02}:{minutes:02}:{seconds:02}.{m_seconds:03}'
49
+
50
+ return f"[{_format_time(start)}-> {_format_time(end)}]:"
51
+
52
+
53
+ @spaces.GPU
54
+ def get_prediction(inputs, task: str, language: Optional[str]):
55
+ generate_kwargs = {"task": task}
56
+ if language:
57
+ generate_kwargs['language'] = language
58
+ prediction = pipe(inputs, return_timestamps=True, generate_kwargs=generate_kwargs)
59
+ text = "".join([c['text'] for c in prediction['chunks']])
60
+ text_timestamped = "\n".join([
61
+ f"{format_time(*c['timestamp'])} {c['text']}" for c in prediction['chunks']
62
+ ])
63
+ return text, text_timestamped
64
+
65
+
66
+ def transcribe(inputs: str, task: str, language: str):
67
+ language = None if language == "none" else language
68
+ if inputs is None:
69
+ raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
70
+ with open(inputs, "rb") as f:
71
+ inputs = f.read()
72
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
73
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
74
+ return get_prediction(inputs, task, language)
75
+
76
+
77
+ demo = gr.Blocks()
78
+ description = (f"Transcribe long-form microphone or audio inputs with the click of a button! Demo uses Kotoba-Whisper "
79
+ f"checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and πŸ€— Transformers to transcribe audio"
80
+ f" files of arbitrary length.")
81
+ title = f"Transcribe Audio with {os.path.basename(MODEL_NAME)}"
82
+ mf_transcribe = gr.Interface(
83
+ fn=transcribe,
84
+ inputs=[
85
+ gr.Audio(sources="microphone", type="filepath"),
86
+ gr.Textbox(lines=1, placeholder="Prompt"),
87
+ gr.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
88
+ gr.Radio(["none", "ja", "en"], label="Language", default="none")
89
+ ],
90
+ outputs=["text", "text"],
91
+ title=title,
92
+ description=description,
93
+ allow_flagging="never",
94
+ )
95
+ file_transcribe = gr.Interface(
96
+ fn=transcribe,
97
+ inputs=[
98
+ gr.Audio(sources="upload", type="filepath", label="Audio file"),
99
+ gr.Textbox(lines=1, placeholder="Prompt"),
100
+ gr.Radio(["transcribe", "translate"], label="Task", default="transcribe"),
101
+ gr.Radio(["none", "ja", "en"], label="Language", default="none")
102
+ ],
103
+ outputs=["text", "text"],
104
+ title=title,
105
+ description=description,
106
+ allow_flagging="never",
107
+ )
108
+ with demo:
109
+ gr.TabbedInterface([mf_transcribe, file_transcribe], ["Microphone", "Audio file"])
110
+ demo.queue(api_open=False, default_concurrency_limit=40).launch(show_api=False, show_error=True)
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ git+https://github.com/huggingface/transformers
2
+ torch