"""
Kindergarten classroom audio review workspace.
Run with: python app.py
"""
from __future__ import annotations
import base64
import html
import math
import os
import re
import tempfile
import uuid
import wave
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
import gradio as gr
# Setup Hugging Face ZeroGPU compatibility decorator
try:
import spaces
GPU_DECORATOR = spaces.GPU
except ImportError:
GPU_DECORATOR = lambda fn: fn
APP_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = APP_DIR / "outputs"
OUTPUT_DIR.mkdir(exist_ok=True)
@dataclass
class Word:
text: str
start: float
end: float
@dataclass
class Segment:
start: float
end: float
text: str
words: List[Word] = field(default_factory=list)
speaker: str = "Speaker 1"
@dataclass
class Event:
start: float
end: float
level: str
kind: str
confidence: float
context: str
reasons: List[str] = field(default_factory=list)
audio_url: str = ""
@dataclass
class SpeakerTurn:
speaker: str
start: float
end: float
def safe_float(value: Any, default: float = 0.0) -> float:
try:
return float(value)
except (TypeError, ValueError):
return default
def fmt_time(seconds: float) -> str:
seconds = max(0.0, safe_float(seconds))
hours, remainder = divmod(int(seconds), 3600)
minutes, secs = divmod(remainder, 60)
if hours > 0:
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
return f"{minutes:02d}:{secs:02d}"
def esc(value: Any) -> str:
return html.escape(str(value), quote=True)
def parse_time_to_seconds(time_str: str) -> float:
if not time_str or not time_str.strip():
return 0.0
parts = time_str.strip().split(":")
try:
if len(parts) == 3:
return float(parts[0]) * 3600 + float(parts[1]) * 60 + float(parts[2])
elif len(parts) == 2:
return float(parts[0]) * 60 + float(parts[1])
return float(parts[0])
except ValueError:
return 0.0
def duration_seconds(path: str) -> float:
try:
import soundfile as sf
info = sf.info(path)
return float(info.frames) / float(info.samplerate)
except Exception:
pass
try:
import librosa
return float(librosa.get_duration(path=path))
except Exception:
pass
try:
with wave.open(path, "rb") as wav_file:
return wav_file.getnframes() / float(wav_file.getframerate())
except Exception:
return 0.0
def trim_audio_segment(path: str, start_str: str, end_str: str) -> Tuple[str, float]:
start_sec = parse_time_to_seconds(start_str)
end_sec = parse_time_to_seconds(end_str)
total_dur = duration_seconds(path)
if end_sec <= 0 or end_sec > total_dur:
end_sec = total_dur
if start_sec >= end_sec:
start_sec = 0.0
if start_sec == 0.0 and end_sec == total_dur:
return path, 0.0
output_trim = OUTPUT_DIR / f"trimmed_{uuid.uuid4().hex[:8]}.wav"
try:
from pydub import AudioSegment
source = AudioSegment.from_file(path)
clip = source[int(start_sec * 1000): int(end_sec * 1000)]
clip.export(str(output_trim), format="wav")
except Exception:
import soundfile as sf
samples, sample_rate = sf.read(path)
begin = int(start_sec * sample_rate)
finish = int(end_sec * sample_rate)
sf.write(str(output_trim), samples[begin:finish], sample_rate, format="WAV")
return str(output_trim), start_sec
def normalize_words(raw_words: Iterable[Dict[str, Any]], segment_start: float, segment_end: float) -> List[Word]:
words: List[Word] = []
for raw in raw_words or []:
text = str(raw.get("word", raw.get("text", ""))).strip()
if not text:
continue
start = safe_float(raw.get("start"), segment_start)
end = safe_float(raw.get("end"), max(start + 0.05, segment_end))
words.append(Word(text=text, start=start, end=max(start, end)))
return words
def fallback_transcript(path: str) -> Tuple[List[Segment], str]:
length = duration_seconds(path)
if length <= 0:
length = 3.0
segment = Segment(
start=0.0,
end=min(length, 8.0),
text="[Demo mode] Add WhisperX model access to transcribe this recording.",
words=[Word("[Demo mode]", 0.0, min(1.0, length)), Word("transcription", 1.0, min(2.0, length))],
)
return [segment], "Demo transcript — WhisperX is not installed or model access is unavailable."
@GPU_DECORATOR
def transcribe_audio(path: str, model_size: str, language: str, hf_token: str) -> Tuple[List[Segment], str]:
try:
import torch
import whisperx
device = "cuda" if torch.cuda.is_available() else "cpu"
compute_type = "float16" if device == "cuda" else "int8"
model = whisperx.load_model(model_size, device, compute_type=compute_type)
kwargs: Dict[str, Any] = {"batch_size": 8}
if language and language != "auto":
kwargs["language"] = language
result = model.transcribe(path, **kwargs)
detected_language = result.get("language", language if language != "auto" else "en")
raw_segments = result.get("segments", [])
try:
model_a, metadata = whisperx.load_align_model(language_code=detected_language, device=device)
result = whisperx.align(raw_segments, model_a, metadata, path, device, return_char_alignments=False)
raw_segments = result.get("segments", raw_segments)
except Exception as align_error:
alignment_note = f" Word alignment fallback: {align_error.__class__.__name__}."
else:
alignment_note = " Word-level timestamps aligned with WhisperX."
segments = []
for raw in raw_segments:
start = safe_float(raw.get("start"))
end = safe_float(raw.get("end"), start + 0.5)
segments.append(
Segment(
start=start,
end=max(start, end),
text=str(raw.get("text", "")).strip(),
words=normalize_words(raw.get("words", []), start, end),
)
)
if segments:
return segments, f"WhisperX transcript ready · {detected_language.upper()} · {device}.{alignment_note}"
except Exception as error:
return (*fallback_transcript(path)[:1], f"Demo transcript · WhisperX unavailable ({error.__class__.__name__}).")
return fallback_transcript(path)
def audio_to_array(path: str, target_sr: int = 16000) -> Tuple[Any, int]:
import librosa
samples, sample_rate = librosa.load(path, sr=target_sr, mono=True)
return samples, sample_rate
@GPU_DECORATOR
def audio_analysis(path: str) -> Tuple[List[Dict[str, Any]], str]:
try:
import numpy as np
import librosa
samples, sample_rate = audio_to_array(path)
if len(samples) < sample_rate // 4:
return [], "Acoustic layer skipped · recording is too short"
hop = max(256, int(sample_rate * 0.25))
frame = max(1024, int(sample_rate * 0.5))
rms = librosa.feature.rms(y=samples, frame_length=frame, hop_length=hop, center=True)[0]
times = librosa.times_like(rms, sr=sample_rate, hop_length=hop)
baseline = float(np.median(rms)) + 1e-6
spread = float(np.median(np.abs(rms - baseline))) + 1e-6
z_scores = (rms - baseline) / (1.4826 * spread)
pitch = librosa.yin(samples, fmin=120, fmax=1200, sr=sample_rate, frame_length=frame, hop_length=hop)
pitch_delta = np.abs(np.diff(pitch, prepend=pitch[0])) / np.maximum(pitch, 1.0)
candidates: List[Dict[str, Any]] = []
for index, z_score in enumerate(z_scores):
if z_score < 2.25 and pitch_delta[index] < 0.22:
continue
start = max(0.0, float(times[index]) - 0.35)
end = min(len(samples) / sample_rate, float(times[index]) + 0.55)
pitch_flag = pitch_delta[index] >= 0.22
kind = "Pitch surge" if pitch_flag and z_score < 3.0 else "Acoustic spike"
candidates.append(
{
"start": start,
"end": end,
"kind": kind,
"energy_z": float(z_score),
"pitch_delta": float(pitch_delta[index]),
"classifier": "",
"classifier_score": 0.0,
}
)
classifier_note = "RMS + pitch analysis"
try:
from transformers import pipeline
classifier_device = -1
try:
import torch
if torch.cuda.is_available():
classifier_device = 0
except Exception:
pass
classifier = pipeline(
"audio-classification",
model=os.getenv("AUDIO_CLASSIFIER_MODEL", "MIT/ast-finetuned-audioset-10-10-0.4593"),
device=classifier_device,
)
labels = classifier(path, top_k=10)
joined = [(str(item.get("label", "")).lower(), safe_float(item.get("score"))) for item in labels]
match_terms = ("scream", "shout", "cry", "violence", "yell", "wail", "sob")
best = next(((label, score) for label, score in joined if any(term in label for term in match_terms)), None)
if best:
for candidate in candidates:
candidate["classifier"], candidate["classifier_score"] = best
classifier_note = f"RMS + pitch + AudioSet classifier ({best[0]} {best[1]:.0%})"
except Exception:
classifier_note += " · optional classifier unavailable"
return candidates, classifier_note
except Exception as error:
return [], f"Acoustic layer unavailable · {error.__class__.__name__}"
SUSPICIOUS_TERMS = {
"shut up": "hostile phrasing",
"stupid": "insult",
"idiot": "insult",
"hit": "physical-harm keyword",
"hurt": "physical-harm keyword",
"stop": "distress/command keyword",
"don't touch": "boundary keyword",
"leave me": "distress phrasing",
"help": "distress keyword",
"no": "possible distress keyword",
}
def text_analysis(segments: Sequence[Segment]) -> List[Dict[str, Any]]:
results: List[Dict[str, Any]] = []
for segment in segments:
lower = segment.text.lower()
hits = [label for term, label in SUSPICIOUS_TERMS.items() if re.search(rf"(? str:
related = [segment.text for segment in segments if segment.end >= start - 3 and segment.start <= end + 3]
return " ".join(related).strip() or "No aligned transcript context"
def classify_event(acoustic: Optional[Dict[str, Any]], text_hit: Optional[Dict[str, Any]], segments: Sequence[Segment]) -> Event:
acoustic = acoustic or {}
text_hit = text_hit or {}
if acoustic and text_hit:
start = min(safe_float(acoustic.get("start"), 0.0), safe_float(text_hit.get("start"), 0.0))
end = max(safe_float(acoustic.get("end"), start + 1.0), safe_float(text_hit.get("end"), start + 1.0))
elif acoustic:
start = safe_float(acoustic.get("start"), 0.0)
end = safe_float(acoustic.get("end"), start + 1.0)
else:
start = safe_float(text_hit.get("start"), 0.0)
end = safe_float(text_hit.get("end"), start + 1.0)
energy_z = safe_float(acoustic.get("energy_z"))
pitch_delta = safe_float(acoustic.get("pitch_delta"))
classifier = str(acoustic.get("classifier", ""))
classifier_score = safe_float(acoustic.get("classifier_score"))
has_scream_label = any(term in classifier for term in ("scream", "shout", "cry", "violence", "yell", "wail", "sob"))
extreme = energy_z >= 4.0
if has_scream_label and classifier_score >= 0.60 and extreme:
level = "Heavy"
elif acoustic and text_hit:
level = "Medium"
else:
level = "Low"
reasons: List[str] = []
if energy_z >= 2.25:
reasons.append(f"RMS energy +{energy_z:.1f}σ")
if pitch_delta >= 0.22:
reasons.append("rapid pitch variation")
if has_scream_label:
reasons.append(f"classifier: {classifier}")
if text_hit:
reasons.extend(text_hit.get("keywords", []))
kind = str(acoustic.get("kind") or text_hit.get("kind") or "Review marker")
confidence = min(0.99, 0.35 + (0.12 if acoustic else 0.0) + (0.18 if text_hit else 0.0) + min(0.30, max(0.0, energy_z) * 0.06))
return Event(
start=start,
end=end,
level=level,
kind=kind,
confidence=confidence,
context=context_for_time(segments, start, end),
reasons=reasons or ["manual review candidate"],
)
def merge_event_candidates(segments: Sequence[Segment], acoustic: Sequence[Dict[str, Any]], text_hits: Sequence[Dict[str, Any]]) -> List[Event]:
events: List[Event] = []
used_text: set[int] = set()
for candidate in acoustic:
nearby_index = next(
(index for index, hit in enumerate(text_hits) if index not in used_text and abs(safe_float(hit.get("start")) - safe_float(candidate.get("start"))) <= 3.0),
None,
)
hit = text_hits[nearby_index] if nearby_index is not None else None
if nearby_index is not None:
used_text.add(nearby_index)
events.append(classify_event(candidate, hit, segments))
for index, hit in enumerate(text_hits):
if index not in used_text:
events.append(classify_event(None, hit, segments))
events.sort(key=lambda item: item.start)
return events
@GPU_DECORATOR
def diarize_audio(path: str, hf_token: str, segments: Sequence[Segment]) -> Tuple[List[SpeakerTurn], str]:
try:
from pyannote.audio import Pipeline
token = hf_token or os.getenv("HF_TOKEN", "")
if not token:
raise RuntimeError("HF_TOKEN not provided")
pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization-3.1", use_auth_token=token)
diarization = pipeline(path)
turns: List[SpeakerTurn] = []
for turn, _, speaker in diarization.itertracks(yield_label=True):
turns.append(SpeakerTurn(str(speaker), float(turn.start), float(turn.end)))
if turns:
return turns, f"Pyannote diarization ready · {len(sorted({turn.speaker for turn in turns}))} voices"
except Exception as error:
fallback_length = max(duration_seconds(path), 3.0)
return [SpeakerTurn("Speaker 1", 0.0, fallback_length)], f"Demo speaker map · Pyannote unavailable ({error.__class__.__name__})"
return [SpeakerTurn("Speaker 1", 0.0, max(duration_seconds(path), 3.0))], "Demo speaker map"
def assign_speakers(segments: Sequence[Segment], turns: Sequence[SpeakerTurn]) -> None:
for segment in segments:
overlap: Dict[str, float] = {}
for turn in turns:
overlap[turn.speaker] = overlap.get(turn.speaker, 0.0) + max(0.0, min(segment.end, turn.end) - max(segment.start, turn.start))
if overlap:
segment.speaker = max(overlap, key=overlap.get)
def wav_bytes_for_segment(path: str, start: float, end: float) -> bytes:
try:
from pydub import AudioSegment
audio = AudioSegment.from_file(path)
clip = audio[max(0, int(start * 1000)): max(1, int(end * 1000))]
with tempfile.NamedTemporaryFile(suffix=".wav") as temporary:
clip.export(temporary.name, format="wav")
temporary.seek(0)
return temporary.read()
except Exception:
try:
import soundfile as sf
samples, sample_rate = sf.read(path)
begin = int(max(0.0, start) * sample_rate)
finish = int(max(start + 0.05, end) * sample_rate)
with tempfile.NamedTemporaryFile(suffix=".wav") as temporary:
sf.write(temporary.name, samples[begin:finish], sample_rate, format="WAV")
temporary.seek(0)
return temporary.read()
except Exception:
return b""
def audio_data_url(path: str, start: float, end: float) -> str:
payload = wav_bytes_for_segment(path, start, end)
if not payload:
return ""
return "data:audio/wav;base64," + base64.b64encode(payload).decode("ascii")
def play_control(url: str, label: str = "Play") -> str:
if not url:
return 'audio unavailable'
return f''
def transcript_html(segments: Sequence[Segment], path: str) -> str:
if not segments:
return '
No transcript yet. Upload a recording and run analysis.
'
rows = []
for index, segment in enumerate(segments):
url = audio_data_url(path, segment.start, segment.end) if path else ""
words = " ".join(
f'{esc(word.text)}'
for word in segment.words
)
body = words or esc(segment.text)
rows.append(
f'
"
def events_html(events: Sequence[Event], path: str, level: str = "All") -> str:
visible = [event for event in events if level == "All" or event.level == level]
if not visible:
return '
No flagged events match this filter.
'
rows = []
for event in visible:
if not event.audio_url and path:
event.audio_url = audio_data_url(path, event.start, event.end)
reasons = ", ".join(event.reasons)
rows.append(
f'
{fmt_time(event.start)}
'
f'
{esc(event.level)}
'
f'
{esc(event.kind)}
{esc(reasons)}
'
f'
{esc(event.context)}
{event.confidence:.0%}
'
f'
{play_control(event.audio_url, "Play")}
'
)
return (
f'
Showing {len(visible)} of {len(events)} review candidates
'
'
Time
Level
Signal
Context
Confidence
Listen
'
'' + "".join(rows) + '
'
)
def search_html(query: str, segments: Sequence[Segment], path: str) -> str:
query = (query or "").strip()
if not query:
return '
Type a word, phrase, or child name to search the aligned transcript.
'
needle = query.casefold()
results = []
for segment in segments:
if needle not in segment.text.casefold():
continue
match = re.search(re.escape(query), segment.text, flags=re.IGNORECASE)
char_position = match.start() if match else 0
timestamp = segment.start
if segment.words:
cursor = 0
for word in segment.words:
word_position = segment.text.casefold().find(word.text.strip().casefold(), cursor)
if word_position < 0:
continue
if word_position <= char_position:
timestamp = word.start
cursor = word_position + len(word.text.strip())
url = audio_data_url(path, max(0.0, timestamp - 1.0), min(segment.end + 1.0, timestamp + 6.0)) if path else ""
highlighted_parts: List[str] = []
cursor = 0
for match in re.finditer(re.escape(query), segment.text, flags=re.IGNORECASE):
highlighted_parts.append(esc(segment.text[cursor:match.start()]))
highlighted_parts.append(f"{esc(match.group(0))}")
cursor = match.end()
highlighted_parts.append(esc(segment.text[cursor:]))
highlighted = "".join(highlighted_parts)
results.append(
f'
' + "".join(results)
def speaker_html(turns: Sequence[SpeakerTurn], path: str) -> str:
speakers: Dict[str, SpeakerTurn] = {}
for turn in turns:
speakers.setdefault(turn.speaker, turn)
cards = []
for speaker, turn in speakers.items():
sample_end = min(turn.end, turn.start + 3.0)
url = audio_data_url(path, turn.start, sample_end) if path else ""
duration = max(0.0, turn.end - turn.start)
cards.append(
f'
{esc(speaker.replace("Speaker ", "S"))}
'
f'
{esc(speaker)}
{fmt_time(duration)} detected · 3 sec preview
'
f'
{play_control(url, "Preview")}
'
)
return '
' + "".join(cards) + '
' if cards else '
No voices detected yet.
'
def export_speaker(path: str, turns: Sequence[SpeakerTurn], speaker: str, tag: str) -> Optional[str]:
selected = [turn for turn in turns if turn.speaker == speaker]
if not selected:
return None
output = OUTPUT_DIR / f"{re.sub(r'[^a-zA-Z0-9_-]+', '_', tag or speaker).strip('_') or 'voice'}_{uuid.uuid4().hex[:8]}.wav"
try:
from pydub import AudioSegment
source = AudioSegment.from_file(path)
merged = AudioSegment.empty()
for turn in selected:
merged += source[max(0, int(turn.start * 1000)): max(1, int(turn.end * 1000))]
merged.export(str(output), format="wav")
except Exception:
import numpy as np
import soundfile as sf
samples, sample_rate = sf.read(path)
chunks = []
for turn in selected:
chunks.append(samples[int(turn.start * sample_rate): int(turn.end * sample_rate)])
if not chunks:
return None
sf.write(str(output), np.concatenate(chunks), sample_rate, format="WAV")
return str(output)
def serialize_state(path: str, segments: Sequence[Segment], events: Sequence[Event], turns: Sequence[SpeakerTurn], notes: Dict[str, str]) -> Dict[str, Any]:
return {
"path": path,
"segments": [asdict(item) for item in segments],
"events": [asdict(item) for item in events],
"turns": [asdict(item) for item in turns],
"notes": notes,
}
def segments_from_state(state: Dict[str, Any]) -> List[Segment]:
return [Segment(**{**item, "words": [Word(**word) for word in item.get("words", [])]}) for item in state.get("segments", [])]
def events_from_state(state: Dict[str, Any]) -> List[Event]:
return [Event(**item) for item in state.get("events", [])]
def turns_from_state(state: Dict[str, Any]) -> List[SpeakerTurn]:
return [SpeakerTurn(**item) for item in state.get("turns", [])]
def render_stats_html(duration: float, segments_count: int, events_count: int, speakers_count: int) -> str:
"""Generate modern analytics summary cards."""
return f"""
Processed Duration
{fmt_time(duration)}
Voices Detected
{speakers_count}
Transcript Segments
{segments_count}
Review Candidates
{events_count}
"""
def analyze_recording(
path: Optional[str],
model_size: str,
language: str,
hf_token: str,
start_time: str,
end_time: str
) -> Tuple[str, str, str, str, str, str, Dict[str, Any], List[str], str]:
if not path:
empty = {"path": "", "segments": [], "events": [], "turns": [], "notes": {}}
return "Upload a WAV or MP3 recording to begin.", "", "", "", "", "", empty, ["Speaker 1"], ""
working_path, offset_seconds = trim_audio_segment(path, start_time, end_time)
segments, transcription_note = transcribe_audio(working_path, model_size, language, hf_token)
acoustic_candidates, acoustic_note = audio_analysis(working_path)
text_hits = text_analysis(segments)
events = merge_event_candidates(segments, acoustic_candidates, text_hits)
turns, diarization_note = diarize_audio(working_path, hf_token, segments)
assign_speakers(segments, turns)
if offset_seconds > 0:
for seg in segments:
seg.start += offset_seconds
seg.end += offset_seconds
for w in seg.words:
w.start += offset_seconds
w.end += offset_seconds
for ev in events:
ev.start += offset_seconds
ev.end += offset_seconds
for turn in turns:
turn.start += offset_seconds
turn.end += offset_seconds
notes = {"transcription": transcription_note, "acoustic": acoustic_note, "diarization": diarization_note}
state = serialize_state(working_path, segments, events, turns, notes)
speaker_names = sorted({turn.speaker for turn in turns}) or ["Speaker 1"]
duration = duration_seconds(working_path)
status = f"Ready · {fmt_time(duration)} processed"
stats_view = render_stats_html(duration, len(segments), len(events), len(speaker_names))
return (
status,
stats_view,
transcript_html(segments, working_path),
events_html(events, working_path),
speaker_html(turns, working_path),
"".join(f'
{esc(v)}
' for v in notes.values()),
state,
speaker_names,
search_html("", segments, working_path),
)
def analyze_recording_ui(path: Optional[str], model_size: str, language: str, hf_token: str, start_time: str, end_time: str):
result = list(analyze_recording(path, model_size, language, hf_token, start_time, end_time))
speaker_names = result[7] or ["Speaker 1"]
result[7] = gr.Dropdown(choices=speaker_names, value=speaker_names[0], label="Voice to export")
return tuple(result)
def filter_events(level: str, state: Dict[str, Any]) -> str:
if not state or not state.get("path"):
return '
Run analysis to populate review candidates.
'
return events_html(events_from_state(state), state["path"], level or "All")
def run_search(query: str, state: Dict[str, Any]) -> str:
if not state or not state.get("path"):
return '