Spaces:
Paused
Paused
File size: 4,381 Bytes
04684e6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | """
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}")
|