cal commited on
Commit
2da24ca
·
1 Parent(s): 287506c

speaches_audio_transcriber

Browse files
Files changed (1) hide show
  1. app.py +128 -0
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import tempfile
4
+ from openai import OpenAI # Import the OpenAI client
5
+ import pandas as pd # Import pandas for data manipulation and Excel export
6
+
7
+ # Ensure your OpenAI API key is set as an environment variable.
8
+ # Example (for testing, but prefer environment variable):
9
+ # os.environ["OPENAI_API_KEY"] = "YOUR_ACTUAL_OPENAI_API_KEY_HERE"
10
+ # Make sure to replace "YOUR_ACTUAL_OPENAI_API_KEY_HERE" with your key
11
+ # if you choose to hardcode it (not recommended for production).
12
+
13
+ # Define the maximum file size for OpenAI's Whisper API (25 MB)
14
+ # Keeping this variable for reference, though chunking logic is removed
15
+ MAX_FILE_SIZE_MB = 25
16
+ MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024
17
+
18
+ def transcribe_verbose(client, audio_file_path):
19
+ """
20
+ Transcribes an audio file using OpenAI's Whisper model,
21
+ requesting verbose JSON output for segment details.
22
+ This function is now used directly for the full file.
23
+ """
24
+ with open(audio_file_path, "rb") as audio_file:
25
+ transcription = client.audio.transcriptions.create(
26
+ model="whisper-1",
27
+ file=audio_file,
28
+ response_format="verbose_json" # Request verbose JSON to get segment times
29
+ )
30
+ return transcription
31
+
32
+ def format_time(seconds):
33
+ """Converts seconds to HH:MM:SS.ms format."""
34
+ minutes, seconds = divmod(seconds, 60)
35
+ hours, minutes = divmod(minutes, 60)
36
+ return f"{int(hours):02}:{int(minutes):02}:{seconds:06.3f}"
37
+
38
+ def transcribe_audio(audio_file_path):
39
+ """
40
+ Transcribes an audio file and generates an Excel file with segment details.
41
+ Note: This version does not handle files larger than 25MB by splitting them.
42
+
43
+ Args:
44
+ audio_file_path (str): The path to the input audio file.
45
+
46
+ Returns:
47
+ tuple: (str, str) - The full transcribed text and the path to the Excel file.
48
+ Returns error messages if transcription fails.
49
+ """
50
+ if not audio_file_path:
51
+ return "Please upload an audio file.", None
52
+
53
+ # Check if the OpenAI API key is available
54
+ openai_api_key = os.getenv("OPENAI_API_KEY")
55
+ if not openai_api_key:
56
+ return "Error: OpenAI API Key not found. Please set the OPENAI_API_KEY environment variable.", None
57
+
58
+ try:
59
+ client = OpenAI(api_key=openai_api_key)
60
+ all_segments_data = [] # To store data for the Excel spreadsheet
61
+ full_text_transcription_parts = [] # To store text parts for the combined transcription
62
+
63
+ # Get file size for informational purposes (no chunking based on it)
64
+ file_size = os.path.getsize(audio_file_path)
65
+ print(f"Input file size: {file_size / (1024 * 1024):.2f} MB")
66
+ if file_size > MAX_FILE_SIZE_BYTES:
67
+ print(f"Warning: File size ({file_size / (1024 * 1024):.2f} MB) exceeds OpenAI's 25MB limit. Transcription might fail.")
68
+ print("Consider manually splitting very large files or reducing audio quality before upload.")
69
+
70
+
71
+ print(f"Transcribing: {audio_file_path} using OpenAI Whisper...")
72
+ transcription = transcribe_verbose(client, audio_file_path) # Direct transcription
73
+
74
+ # The OpenAI client returns an object where segments are accessed as attributes, not dictionary keys.
75
+ if hasattr(transcription, 'segments') and transcription.segments:
76
+ for segment in transcription.segments:
77
+ all_segments_data.append({
78
+ "Start Time": format_time(segment.start), # Access as attribute
79
+ "End Time": format_time(segment.end), # Access as attribute
80
+ "Speaker": "Unknown", # Placeholder for speaker, requires diarization
81
+ "Speech": segment.text.strip() # Access as attribute
82
+ })
83
+ # Collect all segment texts for the full transcription
84
+ full_text_transcription_parts.append(segment.text.strip())
85
+ else:
86
+ print("No segments found in transcription. Falling back to full text.")
87
+ # Fallback to full text if no segments are returned or segments attribute is missing
88
+ if hasattr(transcription, 'text'):
89
+ full_text_transcription_parts.append(transcription.text.strip())
90
+ else:
91
+ full_text_transcription_parts.append("No transcription text available.")
92
+
93
+
94
+ print("Transcription successful. Generating Excel.")
95
+
96
+ # Create Pandas DataFrame and export to Excel
97
+ df = pd.DataFrame(all_segments_data)
98
+
99
+ # Create a temporary Excel file
100
+ with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as temp_excel_file:
101
+ excel_path = temp_excel_file.name
102
+ df.to_excel(excel_path, index=False) # index=False prevents writing DataFrame index to Excel
103
+
104
+ # Join all segment texts into one continuous string for the main display
105
+ return " ".join(full_text_transcription_parts), excel_path
106
+
107
+ except Exception as e:
108
+ print(f"An error occurred during transcription: {e}")
109
+ return f"Error during transcription: {e}", None
110
+
111
+ # Create the Gradio interface
112
+ # gr.Audio for input, gr.Textbox for text output, gr.File for Excel download.
113
+ iface = gr.Interface(
114
+ fn=transcribe_audio,
115
+ inputs=gr.Audio(type="filepath", label="Upload Audio File (MP3, WAV, FLAC, etc.)"),
116
+ outputs=[
117
+ gr.Textbox(label="Full Transcription"),
118
+ gr.File(label="Download Transcription as Excel (.xlsx)")
119
+ ],
120
+ title="Audio File Transcriber (OpenAI Whisper)",
121
+ description="Upload an audio file and get a text transcription using OpenAI's powerful Whisper model. The transcription will be displayed as one continuous text, and also available for download as an Excel spreadsheet with timestamps and speech segments. Note: Speaker identification is not included and would require a separate diarization model. Files larger than 25MB may fail due to OpenAI API limits.",
122
+ allow_flagging="never" # Disables the "Flag" button for this app
123
+ )
124
+
125
+ # Launch the Gradio application
126
+ if __name__ == "__main__":
127
+ print("Launching Gradio application...")
128
+ iface.launch()