KG0101 commited on
Commit
550ced0
·
verified ·
1 Parent(s): 774fabb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -79
app.py CHANGED
@@ -1,11 +1,9 @@
1
  import spaces
2
  import torch
3
-
4
  import gradio as gr
5
  import yt_dlp as youtube_dl
6
- from transformers import pipeline
7
- from transformers.pipelines.audio_utils import ffmpeg_read
8
-
9
  import tempfile
10
  import os
11
 
@@ -16,6 +14,7 @@ YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
16
 
17
  device = 0 if torch.cuda.is_available() else "cpu"
18
 
 
19
  pipe = pipeline(
20
  task="automatic-speech-recognition",
21
  model=MODEL_NAME,
@@ -23,125 +22,104 @@ pipe = pipeline(
23
  device=device,
24
  )
25
 
26
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  @spaces.GPU
28
  def transcribe(inputs, task):
29
  if inputs is None:
30
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
31
-
32
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
33
- return text
34
-
35
-
36
- def _return_yt_html_embed(yt_url):
37
- video_id = yt_url.split("?v=")[-1]
38
- HTML_str = (
39
- f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
40
- " </center>"
41
- )
42
- return HTML_str
43
 
 
44
  def download_yt_audio(yt_url, filename):
45
  info_loader = youtube_dl.YoutubeDL()
46
-
47
  try:
48
  info = info_loader.extract_info(yt_url, download=False)
49
  except youtube_dl.utils.DownloadError as err:
50
  raise gr.Error(str(err))
51
-
52
- file_length = info["duration_string"]
53
- file_h_m_s = file_length.split(":")
54
- file_h_m_s = [int(sub_length) for sub_length in file_h_m_s]
55
-
56
- if len(file_h_m_s) == 1:
57
- file_h_m_s.insert(0, 0)
58
- if len(file_h_m_s) == 2:
59
- file_h_m_s.insert(0, 0)
60
- file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2]
61
-
62
  if file_length_s > YT_LENGTH_LIMIT_S:
63
- yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S))
64
- file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s))
65
- raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.")
66
-
67
  ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
68
-
69
  with youtube_dl.YoutubeDL(ydl_opts) as ydl:
70
- try:
71
- ydl.download([yt_url])
72
- except youtube_dl.utils.ExtractorError as err:
73
- raise gr.Error(str(err))
74
 
 
75
  @spaces.GPU
76
- def yt_transcribe(yt_url, task, max_filesize=75.0):
77
- html_embed_str = _return_yt_html_embed(yt_url)
78
-
79
  with tempfile.TemporaryDirectory() as tmpdirname:
80
  filepath = os.path.join(tmpdirname, "video.mp4")
81
  download_yt_audio(yt_url, filepath)
82
  with open(filepath, "rb") as f:
83
  inputs = f.read()
84
-
85
- inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
86
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
87
-
88
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
 
89
 
90
- return html_embed_str, text
91
-
 
 
 
 
92
 
 
93
  demo = gr.Blocks(theme=gr.themes.Ocean())
94
 
95
  mf_transcribe = gr.Interface(
96
  fn=transcribe,
97
- inputs=[
98
- gr.Audio(sources="microphone", type="filepath"),
99
- gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
100
- ],
101
  outputs="text",
102
  title="Whisper Large V3 Turbo: Transcribe Audio",
103
- description=(
104
- "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
105
- f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
106
- " of arbitrary length."
107
- ),
108
- allow_flagging="never",
109
  )
110
 
111
  file_transcribe = gr.Interface(
112
  fn=transcribe,
113
- inputs=[
114
- gr.Audio(sources="upload", type="filepath", label="Audio file"),
115
- gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"),
116
- ],
117
  outputs="text",
118
- title="Whisper Large V3: Transcribe Audio",
119
- description=(
120
- "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the"
121
- f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files"
122
- " of arbitrary length."
123
- ),
124
- allow_flagging="never",
125
  )
126
 
127
  yt_transcribe = gr.Interface(
128
  fn=yt_transcribe,
129
- inputs=[
130
- gr.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
131
- gr.Radio(["transcribe", "translate"], label="Task", value="transcribe")
132
- ],
133
  outputs=["html", "text"],
134
- title="Whisper Large V3: Transcribe YouTube",
135
- description=(
136
- "Transcribe long-form YouTube videos with the click of a button! Demo uses the checkpoint"
137
- f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of"
138
- " arbitrary length."
139
- ),
140
- allow_flagging="never",
 
 
141
  )
142
 
143
  with demo:
144
- gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
145
 
146
  demo.queue().launch(ssr_mode=False)
147
-
 
1
  import spaces
2
  import torch
 
3
  import gradio as gr
4
  import yt_dlp as youtube_dl
5
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
6
+ from threading import Thread
 
7
  import tempfile
8
  import os
9
 
 
14
 
15
  device = 0 if torch.cuda.is_available() else "cpu"
16
 
17
+ # Initialize the transcription pipeline
18
  pipe = pipeline(
19
  task="automatic-speech-recognition",
20
  model=MODEL_NAME,
 
22
  device=device,
23
  )
24
 
25
+ # Hugging Face Token for the LLM model
26
+ HF_TOKEN = os.getenv("HF_TOKEN") # Make sure to set this in the environment variables
27
+
28
+ # Load tokenizer and model for SOAP note generation
29
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
30
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto")
31
+
32
+ # Prompt for SOAP note generation
33
+ sys_prompt = "You are a world class clinical assistant."
34
+ task_prompt = """
35
+ Convert the following transcribed conversation into a clinical SOAP note.
36
+ The text includes dialogue between a physician and a patient. Please clearly distinguish between the physician's and the patient's statements.
37
+ Extract and organize the information into the relevant sections of a SOAP note:
38
+ - Subjective (symptoms and patient statements),
39
+ - Objective (clinical findings and observations, these might be missing if the physician has not conducted a physical exam or has not verbally stated findings),
40
+ - Assessment (diagnosis or potential diagnoses, objectively provide a top 5 most likely diagnosis based on just the subjective findings, and use the objective findings if available),
41
+ - Plan (treatment and follow-up).
42
+ Ensure the note is concise, clear, and accurately reflects the conversation.
43
+ """
44
+
45
+ # Function to transcribe audio inputs
46
  @spaces.GPU
47
  def transcribe(inputs, task):
48
  if inputs is None:
49
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
 
50
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
51
+ return text
 
 
 
 
 
 
 
 
 
52
 
53
+ # Function to download audio from YouTube
54
  def download_yt_audio(yt_url, filename):
55
  info_loader = youtube_dl.YoutubeDL()
 
56
  try:
57
  info = info_loader.extract_info(yt_url, download=False)
58
  except youtube_dl.utils.DownloadError as err:
59
  raise gr.Error(str(err))
60
+
61
+ file_length_s = sum(x * int(t) for x, t in zip([3600, 60, 1], info["duration_string"].split(":")) if t.isdigit())
 
 
 
 
 
 
 
 
 
62
  if file_length_s > YT_LENGTH_LIMIT_S:
63
+ raise gr.Error(f"Video too long. Maximum allowed duration is {YT_LENGTH_LIMIT_S / 60} minutes.")
64
+
 
 
65
  ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"}
 
66
  with youtube_dl.YoutubeDL(ydl_opts) as ydl:
67
+ ydl.download([yt_url])
 
 
 
68
 
69
+ # Function to transcribe YouTube audio
70
  @spaces.GPU
71
+ def yt_transcribe(yt_url, task):
 
 
72
  with tempfile.TemporaryDirectory() as tmpdirname:
73
  filepath = os.path.join(tmpdirname, "video.mp4")
74
  download_yt_audio(yt_url, filepath)
75
  with open(filepath, "rb") as f:
76
  inputs = f.read()
77
+ inputs = pipe.feature_extractor.ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
 
78
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
 
79
  text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
80
+ return f'<iframe width="500" height="320" src="https://www.youtube.com/embed/{yt_url.split("?v=")[-1]}"> </iframe>', text
81
 
82
+ # Function to generate SOAP notes using LLM
83
+ def generate_soap(transcribed_text):
84
+ prompt = f"{sys_prompt}\n\n{task_prompt}\n{transcribed_text}"
85
+ inputs = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device)
86
+ outputs = model.generate(inputs, max_new_tokens=512)
87
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
88
 
89
+ # Gradio Interfaces for different inputs
90
  demo = gr.Blocks(theme=gr.themes.Ocean())
91
 
92
  mf_transcribe = gr.Interface(
93
  fn=transcribe,
94
+ inputs=[gr.Audio(sources="microphone", type="filepath"), gr.Radio(["transcribe", "translate"], label="Task", value="transcribe")],
 
 
 
95
  outputs="text",
96
  title="Whisper Large V3 Turbo: Transcribe Audio",
97
+ description="Transcribe long-form microphone or audio inputs."
 
 
 
 
 
98
  )
99
 
100
  file_transcribe = gr.Interface(
101
  fn=transcribe,
102
+ inputs=[gr.Audio(sources="upload", type="filepath", label="Audio file"), gr.Radio(["transcribe", "translate"], label="Task", value="transcribe")],
 
 
 
103
  outputs="text",
104
+ title="Whisper Large V3: Transcribe Audio"
 
 
 
 
 
 
105
  )
106
 
107
  yt_transcribe = gr.Interface(
108
  fn=yt_transcribe,
109
+ inputs=[gr.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"), gr.Radio(["transcribe", "translate"], label="Task", value="transcribe")],
 
 
 
110
  outputs=["html", "text"],
111
+ title="Whisper Large V3: Transcribe YouTube"
112
+ )
113
+
114
+ soap_note = gr.Interface(
115
+ fn=generate_soap,
116
+ inputs="text",
117
+ outputs="text",
118
+ title="Generate Clinical SOAP Note",
119
+ description="Convert transcribed conversation to a clinical SOAP note with structured sections (Subjective, Objective, Assessment, Plan)."
120
  )
121
 
122
  with demo:
123
+ gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe, soap_note], ["Microphone", "Audio file", "YouTube", "SOAP Note"])
124
 
125
  demo.queue().launch(ssr_mode=False)