Anupam007 commited on
Commit
dd901a2
·
verified ·
1 Parent(s): b73c874

Create app

Browse files
Files changed (1) hide show
  1. app +200 -0
app ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
4
+ import time
5
+ import os
6
+ import numpy as np
7
+ import soundfile as sf
8
+ import librosa
9
+
10
+ # --- Configuration ---
11
+ # Device selection (GPU if available, else CPU)
12
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
13
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
14
+ print(f"Using device: {device}")
15
+
16
+ # STT Model (Use smaller model for lower latency)
17
+ stt_model_id = "openai/whisper-tiny" # Or "openai/whisper-base". Avoid larger models for streaming.
18
+
19
+ # Summarization Model
20
+ summarizer_model_id = "sshleifer/distilbart-cnn-6-6" # Use a distilled/smaller model for speed
21
+
22
+ # Summarization Interval (seconds) - How often to regenerate the summary
23
+ SUMMARY_INTERVAL = 30.0 # Summarize every 30 seconds
24
+
25
+ # --- Load Models ---
26
+ # (Keep the model loading code exactly the same as before)
27
+ print("Loading STT model...")
28
+ stt_model = AutoModelForSpeechSeq2Seq.from_pretrained(
29
+ stt_model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
30
+ )
31
+ stt_model.to(device)
32
+ processor = AutoProcessor.from_pretrained(stt_model_id)
33
+ stt_pipeline = pipeline(
34
+ "automatic-speech-recognition",
35
+ model=stt_model,
36
+ tokenizer=processor.tokenizer,
37
+ feature_extractor=processor.feature_extractor,
38
+ max_new_tokens=128,
39
+ chunk_length_s=30,
40
+ batch_size=16,
41
+ torch_dtype=torch_dtype,
42
+ device=device,
43
+ )
44
+ print("STT model loaded.")
45
+
46
+ print("Loading Summarization pipeline...")
47
+ summarizer = pipeline(
48
+ "summarization",
49
+ model=summarizer_model_id,
50
+ device=device
51
+ )
52
+ print("Summarization pipeline loaded.")
53
+
54
+
55
+ # --- Helper Functions ---
56
+ # (Keep the format_summary_as_bullets function exactly the same)
57
+ def format_summary_as_bullets(summary_text):
58
+ """Attempts to format a summary text block into bullet points."""
59
+ if not summary_text:
60
+ return ""
61
+ # Simple approach: split by sentences and add bullets.
62
+ # More advanced NLP could be used here.
63
+ sentences = summary_text.replace(". ", ".\n- ").split('\n')
64
+ bullet_summary = "- " + "\n".join(sentences).strip()
65
+ # Remove potential empty bullets
66
+ bullet_summary = "\n".join([line for line in bullet_summary.split('\n') if line.strip() not in ['-', '']])
67
+ return bullet_summary
68
+
69
+
70
+ # --- Processing Function for Streaming ---
71
+ # (Keep the process_audio_stream function exactly the same)
72
+ # This function ONLY processes audio, it doesn't interact with the webcam video
73
+ def process_audio_stream(
74
+ new_chunk_tuple, # Gradio streaming yields (sample_rate, numpy_data)
75
+ accumulated_transcript_state, # gr.State holding the full text
76
+ last_summary_time_state, # gr.State holding the timestamp of the last summary
77
+ current_summary_state # gr.State holding the last generated summary
78
+ ):
79
+
80
+ if new_chunk_tuple is None:
81
+ # Initial call or stream ended, return current state
82
+ return accumulated_transcript_state, current_summary_state, accumulated_transcript_state, last_summary_time_state, current_summary_state
83
+
84
+ sample_rate, audio_chunk = new_chunk_tuple
85
+
86
+ if audio_chunk is None or sample_rate is None or audio_chunk.size == 0:
87
+ # Handle potential empty chunks gracefully
88
+ return accumulated_transcript_state, current_summary_state, accumulated_transcript_state, last_summary_time_state, current_summary_state
89
+
90
+ print(f"Received chunk: {audio_chunk.shape}, Sample Rate: {sample_rate}, Duration: {len(audio_chunk)/sample_rate:.2f}s")
91
+
92
+ # Ensure audio is float32 and mono, as Whisper expects
93
+ if audio_chunk.dtype != np.float32:
94
+ # Normalize assuming input is int16
95
+ # Adjust if your microphone provides different integer types
96
+ audio_chunk = audio_chunk.astype(np.float32) / 32768.0 # Max value for int16 is 32767
97
+
98
+ # --- 1. Transcribe the new chunk ---
99
+ new_text = ""
100
+ try:
101
+ result = stt_pipeline({"sampling_rate": sample_rate, "raw": audio_chunk.copy()})
102
+ new_text = result["text"].strip() if result["text"] else ""
103
+ print(f"Transcription chunk: '{new_text}'")
104
+
105
+ except Exception as e:
106
+ print(f"Error during transcription chunk: {e}")
107
+ new_text = f"[Transcription Error: {e}]"
108
+
109
+ # --- 2. Update Accumulated Transcript ---
110
+ if accumulated_transcript_state and not accumulated_transcript_state.endswith((" ", "\n")) and new_text:
111
+ updated_transcript = accumulated_transcript_state + " " + new_text
112
+ else:
113
+ updated_transcript = accumulated_transcript_state + new_text
114
+
115
+ # --- 3. Periodic Summarization ---
116
+ current_time = time.time()
117
+ new_summary = current_summary_state # Keep the old summary by default
118
+ updated_last_summary_time = last_summary_time_state
119
+
120
+ # Check transcript length to avoid summarizing tiny bits of text too early
121
+ if updated_transcript and len(updated_transcript) > 50 and (current_time - last_summary_time_state > SUMMARY_INTERVAL):
122
+ print(f"Summarizing transcript (length: {len(updated_transcript)})...")
123
+ try:
124
+ # Summarize the *entire* transcript up to this point
125
+ summary_result = summarizer(updated_transcript, max_length=150, min_length=30, do_sample=False)
126
+ if summary_result and isinstance(summary_result, list):
127
+ raw_summary = summary_result[0]['summary_text']
128
+ new_summary = format_summary_as_bullets(raw_summary)
129
+ updated_last_summary_time = current_time # Update time only on successful summary
130
+ print("Summary updated.")
131
+ else:
132
+ print("Summarization did not produce expected output.")
133
+
134
+ except Exception as e:
135
+ print(f"Error during summarization: {e}")
136
+ # Display error in summary box but keep the last known good summary in state
137
+ # To avoid overwriting a potentially useful summary with just an error message
138
+ # We return the error message for display, but not update summary_state with it
139
+ error_display_summary = f"[Summarization Error]\n\nLast good summary:\n{current_summary_state}"
140
+ return updated_transcript, error_display_summary, updated_transcript, last_summary_time_state, current_summary_state
141
+
142
+
143
+ # --- 4. Return Updated State and Outputs ---
144
+ return updated_transcript, new_summary, updated_transcript, updated_last_summary_time, new_summary
145
+
146
+
147
+ # --- Gradio Interface ---
148
+ print("Creating Gradio interface...")
149
+ with gr.Blocks() as demo:
150
+ gr.Markdown("# Real-Time Meeting Notes with Webcam View")
151
+ gr.Markdown("Speak into your microphone. Transcription appears below. Summary updates periodically.")
152
+
153
+ # State variables to store data between stream calls
154
+ transcript_state = gr.State("") # Holds the full transcript
155
+ last_summary_time = gr.State(0.0) # Holds the time the summary was last generated
156
+ summary_state = gr.State("") # Holds the current bullet point summary
157
+
158
+ with gr.Row():
159
+ with gr.Column(scale=1):
160
+ # Input: Microphone stream
161
+ audio_stream = gr.Audio(sources=["microphone"], streaming=True, label="Live Microphone Input", type="numpy")
162
+
163
+ # NEW: Webcam Display
164
+ # Use gr.Image which is simpler for just displaying webcam feed
165
+ # live=True makes it update continuously
166
+ webcam_view = gr.Image(sources=["webcam"], label="Your Webcam", streaming=True) # Use streaming=True for live view
167
+
168
+ with gr.Column(scale=2):
169
+ transcription_output = gr.Textbox(label="Full Transcription", lines=15, interactive=False) # Display only
170
+ summary_output = gr.Textbox(label=f"Bullet Point Summary (Updates ~every {SUMMARY_INTERVAL}s)", lines=10, interactive=False) # Display only
171
+
172
+
173
+ # Connect the streaming audio input to the processing function
174
+ # Note: The webcam component runs independently in the browser, it doesn't feed data here
175
+ audio_stream.stream(
176
+ fn=process_audio_stream,
177
+ inputs=[audio_stream, transcript_state, last_summary_time, summary_state],
178
+ outputs=[transcription_output, summary_output, transcript_state, last_summary_time, summary_state],
179
+ )
180
+
181
+ # Add a button to clear the state if needed
182
+ def clear_state_values():
183
+ print("Clearing state.")
184
+ return "", "", 0.0, "" # Clear transcript display, summary display, reset time state, clear summary state
185
+ # Need separate function to clear states vs displays if they differ
186
+ def clear_state():
187
+ return "", 0.0, "" # Clear transcript_state, last_summary_time, summary_state
188
+
189
+ clear_button = gr.Button("Clear Transcript & Summary")
190
+ # This button clears the display textboxes AND resets the internal states
191
+ clear_button.click(
192
+ fn=lambda: ("", "", "", 0.0, ""), # Return empty values for all outputs/states
193
+ inputs=[],
194
+ outputs=[transcription_output, summary_output, transcript_state, last_summary_time, summary_state]
195
+ )
196
+
197
+
198
+ print("Launching Gradio interface...")
199
+ demo.queue() # Enable queue for handling multiple requests/stream chunks
200
+ demo.launch(debug=True, share=True) # share=True for Colab public link