NarratifAI / src /output /formatter.py
Consulawtech's picture
Deploy NarratifAI ASR system (Whisper + diarization + Claude AI)
04684e6 verified
Raw History Blame Contribute Delete
4.38 kB
"""
Output formatter for transcription results
Author: Maaldeens
License: MIT
"""
from typing import Dict, Optional
import json
import logging
logger = logging.getLogger(__name__)
class OutputFormatter:
"""Formats transcription results into plain text, JSON, SRT, WebVTT, and CSV."""
@staticmethod
def to_text(result: Dict) -> str:
lines = []
for seg in result.get("segments", []):
ts = OutputFormatter._format_timestamp(seg.get("start", 0), "srt")
spk = seg.get("speaker", "")
txt = seg.get("text", "").strip()
if spk:
lines.append(f"{ts} [{spk}] {txt}")
else:
lines.append(f"{ts} {txt}")
return "\n".join(lines) if lines else result.get("text", "")
@staticmethod
def to_json(result: Dict, pretty: bool = True) -> str:
return json.dumps(result, indent=2 if pretty else None, ensure_ascii=False)
@staticmethod
def _format_timestamp(total_seconds: float, fmt: str = "srt") -> str:
"""
Convert a float number of seconds to a subtitle timestamp string.
FIX: Previously used timedelta.seconds which caps at 86399 and drops days.
Now derived from the raw float — correct for any duration.
"""
total_seconds = max(0.0, total_seconds)
hours = int(total_seconds) // 3600
minutes = (int(total_seconds) % 3600) // 60
secs = int(total_seconds) % 60
millis = round((total_seconds - int(total_seconds)) * 1000)
if fmt == "srt":
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
else: # vtt
if hours > 0:
return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millis:03d}"
return f"{minutes:02d}:{secs:02d}.{millis:03d}"
@staticmethod
def to_srt(result: Dict) -> str:
segments = result.get("segments", [])
if not segments:
return ""
lines = []
for i, seg in enumerate(segments, 1):
start = OutputFormatter._format_timestamp(seg.get("start", 0), "srt")
end = OutputFormatter._format_timestamp(seg.get("end", 0), "srt")
text = seg.get("text", "").strip()
lines += [str(i), f"{start} --> {end}", text, ""]
return "\n".join(lines)
@staticmethod
def to_vtt(result: Dict) -> str:
segments = result.get("segments", [])
if not segments:
return "WEBVTT\n\n"
lines = ["WEBVTT", ""]
for seg in segments:
start = OutputFormatter._format_timestamp(seg.get("start", 0), "vtt")
end = OutputFormatter._format_timestamp(seg.get("end", 0), "vtt")
lines += [f"{start} --> {end}", seg.get("text", "").strip(), ""]
return "\n".join(lines)
@staticmethod
def to_csv(result: Dict) -> str:
segments = result.get("segments", [])
if not segments:
return "start,end,speaker,speaker_name,text\n"
lines = ["start,end,speaker,speaker_name,text"]
for seg in segments:
start = seg.get("start", 0)
end = seg.get("end", 0)
speaker = seg.get("speaker", "")
text = seg.get("text", "").strip().replace('"', '""')
lines.append(f'"{start}","{end}","{speaker}","","{text}"')
return "\n".join(lines)
@staticmethod
def format(result: Dict, output_format: str, **kwargs) -> str:
formatters = {
"txt": OutputFormatter.to_text,
"json": lambda r: OutputFormatter.to_json(r, kwargs.get("pretty", True)),
"srt": OutputFormatter.to_srt,
"vtt": OutputFormatter.to_vtt,
"csv": OutputFormatter.to_csv,
}
fn = formatters.get(output_format.lower())
if not fn:
raise ValueError(f"Unsupported output format: {output_format}. Choose from: txt, json, srt, vtt, csv")
return fn(result)
@staticmethod
def save_to_file(result: Dict, output_path: str, fmt: Optional[str] = None):
if fmt is None:
fmt = output_path.rsplit(".", 1)[-1].lower()
content = OutputFormatter.format(result, fmt)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(content)
logger.info(f"Saved transcription to {output_path}")