File size: 14,716 Bytes
e8c9cda 72c8890 6276862 81f8ec2 e8c9cda 22cb4df 87f80fb e8c9cda 7c55ec4 a7ac6e2 7c55ec4 a7ac6e2 7c55ec4 a7ac6e2 7c55ec4 72c8890 7c55ec4 e8c9cda 7c55ec4 a7ac6e2 7c55ec4 a7ac6e2 7c55ec4 0883e72 7c55ec4 72c8890 7c55ec4 a7ac6e2 7c55ec4 a7ac6e2 7c55ec4 a7ac6e2 7c55ec4 a45e589 7c55ec4 a45e589 7c55ec4 a7ac6e2 7c55ec4 72c8890 7c55ec4 72c8890 a9a3ad5 6276862 7c55ec4 6276862 7c55ec4 a9a3ad5 7c55ec4 a9a3ad5 8fc32d0 7c55ec4 a9a3ad5 7c55ec4 a9a3ad5 7c55ec4 a9a3ad5 5944343 7c55ec4 a7ac6e2 5944343 3917c04 5944343 a9a3ad5 d550519 81f8ec2 0253d61 81f8ec2 7c55ec4 0253d61 7c55ec4 07dfabc 7c55ec4 07dfabc 7c55ec4 a9a3ad5 7c55ec4 72c8890 8fc32d0 3917c04 8fc32d0 87f80fb 8fc32d0 3917c04 7c55ec4 3917c04 87f80fb 7c55ec4 8fc32d0 1dc1aca 7ed4daf 7876967 8fc32d0 b265d9b 1dc1aca 7876967 1dc1aca 7876967 1dc1aca b265d9b 1dc1aca b265d9b 1dc1aca b265d9b 1dc1aca b265d9b 8fc32d0 0253d61 8fc32d0 0253d61 8fc32d0 7876967 8fc32d0 b265d9b 8fc32d0 7c55ec4 8fc32d0 3917c04 87f80fb b265d9b 8fc32d0 b265d9b 8fc32d0 7876967 8fc32d0 7876967 8fc32d0 7876967 7c55ec4 a7ac6e2 e50b582 | 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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 | import os
import tempfile
import shutil
from groq import Groq
import gradio as gr
from pydub import AudioSegment
import re
# Initialize the Groq client
client = Groq(api_key=os.environ["keko"])
# def process_audio(audio_file):
# if audio_file is None:
# return None, None, "No audio file provided."
# # Convert to MP3 if not already in MP3 format
# audio = AudioSegment.from_file(audio_file)
# mp3_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
# audio.export(mp3_file.name, format="mp3")
# return mp3_file.name, mp3_file.name, "Audio processed successfully."
# def transcribe_audio(audio_file):
# if audio_file is None:
# return "No audio file provided."
# # Create a transcription of the audio file
# with open(audio_file, "rb") as file:
# transcription = client.audio.transcriptions.create(
# file=(audio_file, file.read()),
# model="whisper-large-v3",
# prompt="fix this dictated Text contains gastroenterology terms. remove words such as commas, newline, periods and replace with appropriate punctuations. apply corrections as specified by the user. keep format, minimal necessary changes only",
# response_format="json",
# temperature=0.0
# )
# return transcription.text
# # Create the Gradio interface using Blocks
# with gr.Blocks(title="Audio Recorder and Transcriber") as demo:
# gr.Markdown("# Audio Recorder and Transcriber")
# gr.Markdown("Record audio or upload a file. You can download the audio or transcribe it.")
# audio_state = gr.State(None)
# with gr.Row():
# audio_input = gr.Audio(sources=["microphone", "upload"], type="filepath", label="Record or Upload Audio")
# with gr.Row():
# process_btn = gr.Button("Process Audio")
# transcribe_btn = gr.Button("Transcribe Audio")
# with gr.Row():
# audio_output = gr.Audio(label="Processed Audio (MP3)", format="mp3")
# process_msg = gr.Textbox(label="Process Status")
# transcription_output = gr.Textbox(label="Transcription", show_copy_button=True)
# def update_audio_state(audio):
# return audio if audio else None
# audio_input.change(
# update_audio_state,
# inputs=[audio_input],
# outputs=[audio_state]
# )
# process_btn.click(
# process_audio,
# inputs=[audio_state],
# outputs=[audio_state, audio_output, process_msg]
# )
# transcribe_btn.click(
# transcribe_audio,
# inputs=[audio_state],
# outputs=[transcription_output]
# )
# # Launch the interface
# demo.launch()
### original: #########################
# def save_audio(audio_file):
# if audio_file is None:
# return None, "No audio file provided."
# # Save the audio file as MP3
# mp3_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
# shutil.copy2(audio_file, mp3_file.name)
# return mp3_file.name, "Audio saved successfully."
# def transcribe_audio(audio_file):
# if audio_file is None:
# return "No audio file provided."
# # Create a transcription of the audio file
# with open(audio_file, "rb") as file:
# transcription = client.audio.transcriptions.create(
# file=(audio_file, file.read()),
# model="whisper-large-v3",
# prompt="text may contain medical gastroenterology terms",
# response_format="json",
# temperature=0.0
# )
# return transcription.text
# # Create the Gradio interface using Blocks
# with gr.Blocks(title="Audio Recorder and Transcriber") as demo:
# gr.Markdown("# Audio Recorder and Transcriber")
# gr.Markdown("Record audio or upload a file. You can download the audio or transcribe it.")
# with gr.Row():
# audio_input = gr.Audio(sources=["microphone", "upload"], type="filepath", label="Record or Upload Audio")
# with gr.Row():
# save_btn = gr.Button("Save Audio")
# transcribe_btn = gr.Button("Transcribe Audio")
# with gr.Row():
# audio_output = gr.Audio(label="Saved Audio (MP3)", format="mp3")
# save_msg = gr.Textbox(label="Save Status")
# transcription_output = gr.Textbox(label="Transcription", show_copy_button=True)
# save_btn.click(
# save_audio,
# inputs=[audio_input],
# outputs=[audio_output, save_msg]
# )
# transcribe_btn.click(
# transcribe_audio,
# inputs=[audio_input],
# outputs=[transcription_output]
# )
# # Launch the interface
# demo.launch()
#### trial send to LLM
#########################
import gradio as gr
import os
from groq import Groq
import tempfile
import shutil
# Initialize the Groq client
client = Groq(api_key=os.environ["keko"])
def check_password(password):
correct_password = "zoo" # Set your desired password here
return password == correct_password
def save_audio(audio_file):
if audio_file is None:
return None, "No audio file provided."
mp3_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
shutil.copy2(audio_file, mp3_file.name)
return mp3_file.name, "Audio saved successfully."
def split_audio(audio_file, chunk_size=25*1024*1024, overlap=10000):
audio = AudioSegment.from_file(audio_file)
duration = len(audio)
chunks = []
start = 0
while start < duration:
end = start + chunk_size
if end > duration:
end = duration
chunk = audio[start:end]
if len(chunk.raw_data) > chunk_size:
end = start + (chunk_size // chunk.frame_width) * chunk.frame_width
chunk = audio[start:end]
chunks.append(chunk)
start = end - overlap
return chunks
def transcribe_audio(audio_file):
if audio_file is None:
return "No audio file provided."
file_size = os.path.getsize(audio_file)
max_size = 25 * 1024 * 1024 # 25 MB in bytes
if file_size <= max_size:
# If the file is small enough, process it directly
with open(audio_file, "rb") as file:
transcription = client.audio.transcriptions.create(
file=(audio_file, file.read()),
model="whisper-large-v3",
prompt="fix this dictated Text contains gastroenterology terms. remove words such as commas, newline, periods and replace with appropriate punctuations. apply corrections as specified by the user. keep format, minimal necessary changes only",
response_format="json",
temperature=0.0
)
return transcription.text
else:
# If the file is too large, split it and process chunks
chunks = split_audio(audio_file)
transcriptions = []
for i, chunk in enumerate(chunks):
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:
chunk.export(temp_file.name, format="mp3")
with open(temp_file.name, "rb") as file:
transcription = client.audio.transcriptions.create(
file=(f"chunk_{i}.mp3", file.read()),
model="whisper-large-v3",
prompt="fix this dictated Text contains gastroenterology terms. ",
response_format="json",
temperature=0.0
)
transcriptions.append(transcription.text)
os.unlink(temp_file.name)
return " ".join(transcriptions)
## function to parse text into dictionary of prompts
def parse_text_to_dict(text):
sections = re.split(r"\n#/\s*", text.strip()) # Split only at "#/"
parsed_dict = {}
for section in sections:
if not section.strip(): # Skip empty sections
continue
lines = section.split("\n", 1) # Split into title and content
title = lines[0].strip().lstrip("#/ ") # Ensure "#/" is removed
content = lines[1].strip() if len(lines) > 1 else "" # Remaining text is the value
parsed_dict[title] = content
return parsed_dict
# load the prompts:
with open("primpts.txt", "r", encoding="utf-8") as file:
contentt = file.read()
contentt = parse_text_to_dict(contentt)
def generate_text(text, prompt_type):
if not text:
return "No text provided."
prompts = contentt
selected_prompt = prompts.get(prompt_type, "You are a helpful assistant. Process the following text.")
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": selected_prompt},
{"role": "user", "content": text}
],
max_tokens=4000,
temperature=0.1
)
return response.choices[0].message.content
# Define the new function for "Transcribe & Fix"
def transcribe_and_generate(audio_file, prompt_type):
# Transcribe the audio
transcription = transcribe_audio(audio_file)
# Generate the text based on the transcription and selected prompt
generated_text = generate_text(transcription, prompt_type)
return transcription, generated_text
# Define a new function that combines save, transcribe, and fix
def save_transcribe_fix(audio_file, prompt_type):
# Step 1: Save the audio
saved_audio, save_status = save_audio(audio_file)
if not saved_audio:
return None, save_status, None # Return error message if saving fails
# Step 2: Transcribe the audio
transcription = transcribe_audio(saved_audio)
# Step 3: Generate the fixed text
fixed_text = generate_text(transcription, prompt_type)
return saved_audio, transcription, fixed_text
# ------------------------------------------------
# Create the Gradio interface using Blocks
# -------------------------------------------------
# Update Gradio UI with a new button
with gr.Blocks(title="Audio Recorder, Transcriber, and Text Generator") as demo:
gr.Markdown("# Audio Recorder, Transcriber, and Text Generator")
gr.Markdown("Enter the correct password to access the application.")
with gr.Group() as login_container:
password_input = gr.Textbox(type="password", label="Enter Password")
login_button = gr.Button("Login")
login_message = gr.Markdown()
with gr.Column(visible=False) as main_interface:
gr.Markdown("Record audio, transcribe it, or enter text manually, and optionally generate text based on the input.")
input_toggle = gr.Checkbox(label="Use Manual Text Input Instead of Audio", value=False)
# Audio section including transcription output
with gr.Column() as audio_section:
audio_input = gr.Audio(sources=["microphone", "upload"], type="filepath", label="Record or Upload Audio")
with gr.Row():
save_btn = gr.Button("Save Audio")
transcribe_btn = gr.Button("Transcribe Audio")
transcribe_fix_btn = gr.Button("Transcribe & Fix")
save_transcribe_fix_btn = gr.Button("Save, Transcribe & Fix")
with gr.Row():
audio_output = gr.Audio(label="Saved Audio (MP3)", format="mp3")
save_msg = gr.Textbox(label="Save Status")
transcription_output = gr.Textbox(label="Transcription", show_copy_button=True)
# Text input section (starts hidden)
text_input = gr.Textbox(label="Enter Text Manually", visible=False)
# Toggle input sources (audio or text)
input_toggle.change(
lambda use_text: (
gr.update(visible=not use_text), # Hide audio section if using text input
gr.update(visible=use_text), # Show text input when checked
gr.update(visible=not use_text) # Hide transcription output when using text input
),
inputs=[input_toggle],
outputs=[audio_section, text_input, transcription_output]
)
with gr.Row():
prompt_type = gr.Dropdown(
choices=list(contentt.keys()), # Get dictionary keys as choices
label="Select Text Generation Type",
value=list(contentt.keys())[0] # Default to the first key
)
generate_btn = gr.Button("Generate Text")
generated_text_output = gr.Textbox(label="Generated Text", show_copy_button=True)
# Actions for audio-related inputs
save_btn.click(
save_audio,
inputs=[audio_input],
outputs=[audio_output, save_msg]
)
transcribe_btn.click(
transcribe_audio,
inputs=[audio_input],
outputs=[transcription_output]
)
transcribe_fix_btn.click(
transcribe_and_generate,
inputs=[audio_input, prompt_type],
outputs=[transcription_output, generated_text_output]
)
save_transcribe_fix_btn.click(
save_transcribe_fix,
inputs=[audio_input, prompt_type],
outputs=[audio_output, transcription_output, generated_text_output]
)
# Automatically detect if text or audio should be used
def determine_input(audio, text, prompt):
if text.strip(): # If text is entered, use it
return generate_text(text, prompt)
elif audio: # Otherwise, check if audio exists and use it
return generate_text(transcription_output.value, prompt)
else:
return "Please provide either text or audio."
generate_btn.click(
determine_input,
inputs=[audio_input, text_input, prompt_type],
outputs=[generated_text_output]
)
def login(password):
if check_password(password):
return {
login_container: gr.update(visible=False), # Hide login UI
main_interface: gr.update(visible=True), # Show main interface
login_message: gr.update(value="Login successful.", visible=True)
}
else:
return {
login_message: gr.update(value="Incorrect password. Please try again.", visible=True)
}
login_button.click(
login,
inputs=[password_input],
outputs=[login_container, main_interface, login_message]
)
demo.launch(share=True) |