Spaces:
Running on Zero
Running on Zero
Download clean_sub.py from jumannendange/dl-proxy: direct link, hf CLI and curl.
- Browser
- Download file 1.64 kB
-
https://huggingface.co/spaces/jumannendange/dl-proxy/resolve/main/clean_sub.py
- Command line
-
hf download hf://spaces/jumannendange/dl-proxy/clean_sub.py
-
curl -L -o clean_sub.py https://huggingface.co/spaces/jumannendange/dl-proxy/resolve/main/clean_sub.py
1.64 kB
| import re | |
| _TS = re.compile(r'(\d{1,2}):(\d\d):(\d\d)[,.](\d{1,3})\s*-->\s*(\d{1,2}):(\d\d):(\d\d)[,.](\d{1,3})') | |
| def decode_sub(raw: bytes) -> str: | |
| """UTF-16 (BOM) -> UTF-8 -> Windows-1252, kwa mpangilio huo.""" | |
| if raw[:2] in (b'\xff\xfe', b'\xfe\xff'): | |
| return raw.decode('utf-16', errors='replace') | |
| try: | |
| return raw.decode('utf-8') | |
| except UnicodeDecodeError: | |
| return raw.decode('cp1252', errors='replace') | |
| def _fmt(h, m, s, ms): | |
| return f'{int(h):02d}:{m}:{s},{ms.ljust(3, "0")[:3]}' | |
| def clean_srt(raw: bytes) -> str: | |
| """Geuza manukuu yoyote (SRT, WEBVTT, mchanganyiko wenye BOM/koma/nukta) | |
| kuwa SRT safi yenye namba. Rudisha '' kama hakuna cue hata moja.""" | |
| text = decode_sub(raw).replace('\ufeff', '').replace('\r\n', '\n').replace('\r', '\n') | |
| lines = text.split('\n') | |
| cues, i = [], 0 | |
| while i < len(lines): | |
| m = _TS.search(lines[i]) | |
| if not m: | |
| i += 1 | |
| continue | |
| i += 1 | |
| body = [] | |
| while i < len(lines) and lines[i].strip(): | |
| if _TS.search(lines[i]): | |
| break | |
| if lines[i].strip().isdigit() and i + 1 < len(lines) and _TS.search(lines[i + 1]): | |
| break | |
| body.append(lines[i]) | |
| i += 1 | |
| txt = re.sub(r'\{\\[^}]*\}', '', '\n'.join(body)) | |
| txt = re.sub(r'</?font[^>]*>', '', txt, flags=re.I).strip() | |
| if txt: | |
| g = m.groups() | |
| cues.append(f'{_fmt(*g[0:4])} --> {_fmt(*g[4:8])}\n{txt}') | |
| if not cues: | |
| return '' | |
| return '\n\n'.join(f'{n}\n{c}' for n, c in enumerate(cues, 1)) + '\n' | |