Spaces:
Paused
Paused
Download src/output/formatter.py from Consulawtech/NarratifAI: direct link, hf CLI and curl.
- Browser
- Download file 4.38 kB
-
https://huggingface.co/spaces/Consulawtech/NarratifAI/resolve/main/src/output/formatter.py
- Command line
-
hf download hf://spaces/Consulawtech/NarratifAI/src/output/formatter.py
-
curl -L -o formatter.py https://huggingface.co/spaces/Consulawtech/NarratifAI/resolve/main/src/output/formatter.py
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.""" | |
| 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", "") | |
| def to_json(result: Dict, pretty: bool = True) -> str: | |
| return json.dumps(result, indent=2 if pretty else None, ensure_ascii=False) | |
| 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}" | |
| 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) | |
| 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) | |
| 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) | |
| 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) | |
| 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}") | |