Download app.py from omlad/Gan: direct link, hf CLI and curl.
- Browser
- Download file 39.7 kB
-
https://huggingface.co/spaces/omlad/Gan/resolve/main/app.py
- Command line
-
hf download hf://spaces/omlad/Gan/app.py
-
curl -L -o app.py https://huggingface.co/spaces/omlad/Gan/resolve/main/app.py
39.7 kB
"""
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"(?<!\w){re.escape(term)}(?!\w)", lower)]
if hits:
results.append(
{
"start": segment.start,
"end": segment.end,
"kind": "Text flag",
"keywords": hits,
"context": segment.text,
}
)
return results
def context_for_time(segments: Sequence[Segment], start: float, end: float) -> 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 '<span class="muted">audio unavailable</span>'
return f'<button class="play-btn" onclick="this.nextElementSibling.play()">▶ {esc(label)}</button><audio preload="none" src="{url}"></audio>'
def transcript_html(segments: Sequence[Segment], path: str) -> str:
if not segments:
return '<div class="empty-state">No transcript yet. Upload a recording and run analysis.</div>'
rows = []
for index, segment in enumerate(segments):
url = audio_data_url(path, segment.start, segment.end) if path else ""
words = " ".join(
f'<span class="word" data-start="{word.start:.3f}" title="{fmt_time(word.start)}">{esc(word.text)}</span>'
for word in segment.words
)
body = words or esc(segment.text)
rows.append(
f'<div class="transcript-row"><div class="timestamp">{fmt_time(segment.start)}<span>→ {fmt_time(segment.end)}</span></div>'
f'<div class="speaker-chip">{esc(segment.speaker)}</div><div class="transcript-copy">{body}</div>'
f'<div class="row-action">{play_control(url, "Play")}</div></div>'
)
return '<div class="transcript-list">' + "".join(rows) + "</div>"
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 '<div class="empty-state">No flagged events match this filter.</div>'
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'<tr><td><span class="time-pill">{fmt_time(event.start)}</span></td>'
f'<td><span class="severity {event.level.lower()}">{esc(event.level)}</span></td>'
f'<td><strong>{esc(event.kind)}</strong><div class="reason">{esc(reasons)}</div></td>'
f'<td class="context">{esc(event.context)}</td><td>{event.confidence:.0%}</td>'
f'<td>{play_control(event.audio_url, "Play")}</td></tr>'
)
return (
f'<div class="table-meta">Showing {len(visible)} of {len(events)} review candidates</div>'
'<div class="table-wrap"><table class="events-table"><thead><tr><th>Time</th><th>Level</th><th>Signal</th><th>Context</th><th>Confidence</th><th>Listen</th></tr></thead>'
'<tbody>' + "".join(rows) + '</tbody></table></div>'
)
def search_html(query: str, segments: Sequence[Segment], path: str) -> str:
query = (query or "").strip()
if not query:
return '<div class="empty-state">Type a word, phrase, or child name to search the aligned transcript.</div>'
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"<mark>{esc(match.group(0))}</mark>")
cursor = match.end()
highlighted_parts.append(esc(segment.text[cursor:]))
highlighted = "".join(highlighted_parts)
results.append(
f'<div class="search-result"><div class="search-top"><span class="time-pill">{fmt_time(timestamp)}</span>'
f'<span class="speaker-chip">{esc(segment.speaker)}</span>{play_control(url, "Quick play")}</div>'
f'<div class="search-text">{highlighted}</div><div class="search-context">Context · {esc(context_for_time(segments, segment.start, segment.end))}</div></div>'
)
if not results:
return f'<div class="empty-state">No occurrences found for “{esc(query)}”.</div>'
return f'<div class="table-meta">{len(results)} occurrence(s) · case-insensitive</div>' + "".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'<div class="speaker-card"><div class="speaker-avatar">{esc(speaker.replace("Speaker ", "S"))}</div>'
f'<div><div class="speaker-name">{esc(speaker)}</div><div class="speaker-meta">{fmt_time(duration)} detected · 3 sec preview</div></div>'
f'<div class="speaker-play">{play_control(url, "Preview")}</div></div>'
)
return '<div class="speaker-grid">' + "".join(cards) + '</div>' if cards else '<div class="empty-state">No voices detected yet.</div>'
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"""
<div class="stats-grid">
<div class="stat-card">
<div class="stat-label">Processed Duration</div>
<div class="stat-value">{fmt_time(duration)}</div>
</div>
<div class="stat-card">
<div class="stat-label">Voices Detected</div>
<div class="stat-value">{speakers_count}</div>
</div>
<div class="stat-card">
<div class="stat-label">Transcript Segments</div>
<div class="stat-value">{segments_count}</div>
</div>
<div class="stat-card alert">
<div class="stat-label">Review Candidates</div>
<div class="stat-value">{events_count}</div>
</div>
</div>
"""
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'<div class="note"><span class="note-dot"></span>{esc(v)}</div>' 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 '<div class="empty-state">Run analysis to populate review candidates.</div>'
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 '<div class="empty-state">Run analysis before searching.</div>'
return search_html(query, segments_from_state(state), state["path"])
def do_export(speaker: str, tag: str, state: Dict[str, Any]) -> Tuple[Optional[str], str]:
if not state or not state.get("path"):
return None, "Run analysis before exporting a voice."
output = export_speaker(state["path"], turns_from_state(state), speaker, tag)
if not output:
return None, f"No audio segments found for {speaker}."
return output, f"Export ready · {speaker} · tagged as {tag or speaker}"
CSS = """
@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
:root {
--font: 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif;
--bg: #090d16;
--card-bg: rgba(18, 26, 43, 0.75);
--card-border: rgba(255, 255, 255, 0.08);
--accent: #8b5cf6;
--accent-glow: rgba(139, 92, 246, 0.35);
--cyan: #38bdf8;
--pink: #f43f5e;
--ink: #f1f5f9;
--muted: #94a3b8;
}
body, .gradio-container {
background-color: var(--bg) !important;
font-family: var(--font) !important;
color: var(--ink) !important;
}
.gradio-container {
max-width: 1440px !important;
padding: 24px !important;
}
/* Hero Section */
.hero {
position: relative;
padding: 36px 40px;
border: 1px solid var(--card-border);
border-radius: 24px;
background: radial-gradient(circle at 90% -20%, rgba(139, 92, 246, 0.25), transparent 50%),
radial-gradient(circle at 10% 120%, rgba(56, 189, 248, 0.15), transparent 40%),
rgba(15, 23, 42, 0.8);
backdrop-filter: blur(16px);
margin-bottom: 24px;
box-shadow: 0 20px 40px -15px rgba(0, 0, 0, 0.5);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--cyan);
text-transform: uppercase;
letter-spacing: 0.15em;
font-size: 11px;
font-weight: 800;
margin-bottom: 12px;
}
.hero h1 {
font-size: 36px;
font-weight: 800;
letter-spacing: -0.03em;
margin: 0 0 10px;
background: linear-gradient(135deg, #ffffff 30%, #a78bfa 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.hero p {
color: var(--muted);
max-width: 680px;
font-size: 15px;
line-height: 1.6;
margin: 0;
}
/* Glass Panels */
.panel {
border: 1px solid var(--card-border) !important;
border-radius: 20px !important;
background: var(--card-bg) !important;
backdrop-filter: blur(12px) !important;
padding: 22px !important;
box-shadow: 0 10px 30px -10px rgba(0,0,0,0.3);
}
.section-title {
font-size: 15px;
font-weight: 700;
color: #ffffff;
margin-bottom: 16px;
letter-spacing: -0.01em;
}
/* Stats Row */
.stats-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.stat-card {
background: rgba(30, 41, 59, 0.5);
border: 1px solid var(--card-border);
border-radius: 14px;
padding: 14px 16px;
}
.stat-card.alert {
border-color: rgba(244, 63, 94, 0.3);
background: rgba(244, 63, 94, 0.08);
}
.stat-label {
font-size: 11px;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 600;
}
.stat-value {
font-size: 20px;
font-weight: 800;
color: #ffffff;
margin-top: 4px;
}
/* Form Elements */
input, select, textarea {
background: rgba(15, 23, 42, 0.6) !important;
border: 1px solid var(--card-border) !important;
border-radius: 12px !important;
color: var(--ink) !important;
}
input:focus, select:focus {
border-color: var(--accent) !important;
box-shadow: 0 0 0 2px var(--accent-glow) !important;
}
button.primary {
background: linear-gradient(135deg, #7c3aed, #6366f1) !important;
border: none !important;
border-radius: 12px !important;
font-weight: 700 !important;
box-shadow: 0 4px 20px var(--accent-glow) !important;
transition: all 0.2s ease !important;
}
button.primary:hover {
transform: translateY(-1px);
box-shadow: 0 6px 24px var(--accent-glow) !important;
}
/* Transcript & Dynamic Rows */
.transcript-list {
max-height: 520px;
overflow-y: auto;
padding-right: 6px;
}
.transcript-row {
display: grid;
grid-template-columns: 80px 100px 1fr auto;
gap: 14px;
align-items: start;
padding: 14px 12px;
border-bottom: 1px solid rgba(255, 255, 255, 0.04);
border-radius: 10px;
transition: background 0.15s ease;
}
.transcript-row:hover {
background: rgba(255, 255, 255, 0.03);
}
.timestamp {
color: var(--cyan);
font-weight: 700;
font-size: 12px;
}
.timestamp span {
display: block;
color: var(--muted);
font-weight: 400;
font-size: 11px;
}
.speaker-chip {
display: inline-block;
background: rgba(139, 92, 246, 0.15);
border: 1px solid rgba(139, 92, 246, 0.3);
color: #c4b5fd;
border-radius: 20px;
padding: 3px 10px;
font-size: 11px;
font-weight: 600;
text-align: center;
}
.play-btn {
background: rgba(255, 255, 255, 0.06);
border: 1px solid var(--card-border);
color: #ffffff;
border-radius: 8px;
padding: 6px 12px;
font-size: 11px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s ease;
}
.play-btn:hover {
background: rgba(56, 189, 248, 0.15);
border-color: var(--cyan);
color: var(--cyan);
}
/* Event Table */
.table-wrap {
border: 1px solid var(--card-border);
border-radius: 14px;
overflow: hidden;
}
.events-table {
width: 100%;
border-collapse: collapse;
}
.events-table th {
background: rgba(15, 23, 42, 0.8);
color: var(--muted);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 12px 16px;
text-align: left;
}
.events-table td {
padding: 14px 16px;
border-top: 1px solid rgba(255, 255, 255, 0.04);
font-size: 13px;
}
.severity {
padding: 4px 10px;
border-radius: 20px;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
}
.severity.low { background: rgba(34, 197, 94, 0.15); color: #4ade80; }
.severity.medium { background: rgba(234, 179, 8, 0.15); color: #facc15; }
.severity.heavy { background: rgba(244, 63, 94, 0.15); color: #f43f5e; }
/* Empty state */
.empty-state {
border: 1px dashed var(--card-border);
border-radius: 14px;
padding: 40px;
text-align: center;
color: var(--muted);
font-size: 13px;
}
footer { display: none !important; }
"""
def build_app():
with gr.Blocks(title="Little Ears · Classroom Audio Intelligence") as demo:
state = gr.State({})
gr.HTML(
'<div class="hero">'
'<div class="eyebrow">Little Ears · Audio Intelligence</div>'
'<h1>Classroom Audio Review Workspace</h1>'
'<p>Filter noise, transcribe multi-hour recordings, isolate individual voices, and auto-detect suspicious acoustic events in context.</p>'
'</div>'
)
with gr.Row(equal_height=False):
with gr.Column(scale=1, min_width=320):
with gr.Group(elem_classes="panel"):
gr.HTML('<div class="section-title">1 · Source Audio & Time Range</div>')
audio = gr.Audio(label="Upload Classroom Recording", sources=["upload"], type="filepath", format="wav")
with gr.Row():
start_time = gr.Textbox(label="Start Range", placeholder="02:45:00", value="")
end_time = gr.Textbox(label="End Range", placeholder="03:15:00", value="")
model_size = gr.Dropdown(["tiny", "base", "small", "medium", "large-v3"], value="small", label="WhisperX Model")
language = gr.Dropdown(["auto", "en", "he", "es", "ar", "fr"], value="auto", label="Language")
token = gr.Textbox(label="Hugging Face Token", type="password", placeholder="Optional: For Pyannote models")
analyze = gr.Button("Analyze Audio Segment", variant="primary", size="lg")
status = gr.Markdown("Upload a recording to begin.", elem_classes="status")
notes = gr.HTML('<div class="notes"></div>')
with gr.Column(scale=2, min_width=500):
with gr.Group(elem_classes="panel"):
stats_view = gr.HTML(render_stats_html(0, 0, 0, 0))
gr.HTML('<div class="section-title">Aligned Word Transcript</div>')
transcript = gr.HTML('<div class="empty-state">Your chronological transcript will appear here.</div>')
with gr.Tabs():
with gr.Tab("Suspicion Review"):
with gr.Group(elem_classes="panel"):
with gr.Row():
gr.Markdown("Review Candidates", elem_classes="section-title")
event_filter = gr.Dropdown(["All", "Low", "Medium", "Heavy"], value="All", label="Filter", scale=0, min_width=140)
events = gr.HTML('<div class="empty-state">Run analysis to surface review candidates.</div>')
with gr.Tab("Voices & Export"):
with gr.Group(elem_classes="panel"):
gr.HTML('<div class="section-title">Speaker Map & Previews</div>')
speakers = gr.HTML('<div class="empty-state">Run analysis to isolate distinct voices.</div>')
with gr.Row():
speaker_select = gr.Dropdown(["Speaker 1"], value="Speaker 1", label="Voice to Export")
speaker_tag = gr.Textbox(value="selected-child", label="Export Voice Tag")
export = gr.Button("Export Merged Voice", variant="primary")
export_file = gr.File(label="Merged WAV Download")
export_status = gr.Markdown("")
with gr.Tab("Search Transcript"):
with gr.Group(elem_classes="panel"):
gr.HTML('<div class="section-title">Contextual Word & Name Search</div>')
search = gr.Textbox(label="Search Query", placeholder="Enter child name or phrase (e.g. Maya, stop)", autofocus=True)
search_results = gr.HTML('<div class="empty-state">Type a word or name to search the transcript.</div>')
analyze.click(
analyze_recording_ui,
inputs=[audio, model_size, language, token, start_time, end_time],
outputs=[status, stats_view, transcript, events, speakers, notes, state, speaker_select, search_results],
)
event_filter.change(filter_events, inputs=[event_filter, state], outputs=[events])
search.input(run_search, inputs=[search, state], outputs=[search_results])
search.change(run_search, inputs=[search, state], outputs=[search_results])
search.submit(run_search, inputs=[search, state], outputs=[search_results])
export.click(do_export, inputs=[speaker_select, speaker_tag, state], outputs=[export_file, export_status])
return demo
if __name__ == "__main__":
app = build_app()
app.launch(
server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
server_port=int(os.getenv("GRADIO_SERVER_PORT", "7860")),
css=CSS,
theme=gr.themes.Base(primary_hue="violet", neutral_hue="slate"),
)
"""
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)
class Word:
text: str
start: float
end: float
class Segment:
start: float
end: float
text: str
words: List[Word] = field(default_factory=list)
speaker: str = "Speaker 1"
class Event:
start: float
end: float
level: str
kind: str
confidence: float
context: str
reasons: List[str] = field(default_factory=list)
audio_url: str = ""
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