kjbytes commited on
Commit
cfff3e1
·
1 Parent(s): f786792

feat: add SRT subtitle generation and improve security

Browse files

- Generate SRT subtitle files alongside WAV audio output by splitting text on sentence boundaries and proportionally distributing timestamps across the audio duration.
- Extend download endpoint to serve both .wav and .srt files with correct MIME types.
- Harden API key authentication: strip whitespace from env var and user input, use `secrets.compare_digest` for constant-time comparison, and reject missing keys.
- Configure Uvicorn with `--forwarded-allow-ips=*` so the Spaces proxy is trusted and `request.base_url` yields https.
- Document upstream constraints (max_new_tokens truncation, watermark) in README and code comments.

Files changed (5) hide show
  1. Dockerfile +2 -1
  2. README.md +5 -0
  3. app.py +39 -7
  4. test_download_name.py +2 -2
  5. test_srt.py +18 -0
Dockerfile CHANGED
@@ -30,4 +30,5 @@ RUN pip install --no-cache-dir "numpy<2" "cython<3" setuptools wheel \
30
  COPY --chown=user app.py .
31
 
32
  EXPOSE 7860
33
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
30
  COPY --chown=user app.py .
31
 
32
  EXPOSE 7860
33
+ # forwarded-allow-ips: trust the Spaces proxy so request.base_url yields https, not http.
34
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--forwarded-allow-ips", "*"]
README.md CHANGED
@@ -28,6 +28,11 @@ curl -X POST https://<user>-<space>.hf.space/tts \
28
  Then `curl -O <url>` — the download endpoint is public (unguessable uuid).
29
 
30
  Params: `text` (required, ≤1000 chars), `lang` (default `en`), `exaggeration` (0–2), `cfg_weight` (0–1).
 
 
 
 
 
31
  Supported langs: ar, da, de, el, en, es, fi, fr, he, hi, it, ja, ko, ms, nl, no, pl, pt, ru, sv, sw, tr, zh.
32
 
33
  ## Notes
 
28
  Then `curl -O <url>` — the download endpoint is public (unguessable uuid).
29
 
30
  Params: `text` (required, ≤1000 chars), `lang` (default `en`), `exaggeration` (0–2), `cfg_weight` (0–1).
31
+
32
+ Output is 24kHz mono WAV and always carries Resemble's Perth watermark. Defaults suit most
33
+ prompts; for more expressive reads the model card suggests `cfg_weight` ~0.3 with
34
+ `exaggeration` ~0.7. Caveat: upstream `generate()` hardcodes `max_new_tokens=1000` (~40s of
35
+ audio), so text beyond roughly 600-700 chars is silently truncated.
36
  Supported langs: ar, da, de, el, en, es, fi, fr, he, hi, it, ja, ko, ms, nl, no, pl, pt, ru, sv, sw, tr, zh.
37
 
38
  ## Notes
app.py CHANGED
@@ -1,11 +1,14 @@
1
  import os
 
 
2
  import uuid
3
 
4
  from fastapi import Depends, FastAPI, HTTPException, Header, Request
5
  from fastapi.responses import FileResponse
6
  from pydantic import BaseModel, Field
7
 
8
- API_KEY = os.environ["API_KEY"]
 
9
  OUT_DIR = os.environ.get("OUT_DIR", "/tmp/audio")
10
  os.makedirs(OUT_DIR, exist_ok=True)
11
 
@@ -14,7 +17,7 @@ _model = None
14
 
15
 
16
  def auth(x_api_key: str = Header(None)):
17
- if x_api_key != API_KEY:
18
  raise HTTPException(401, "bad api key")
19
 
20
 
@@ -38,6 +41,8 @@ def model():
38
 
39
 
40
  class TTSRequest(BaseModel):
 
 
41
  text: str = Field(min_length=1, max_length=1000)
42
  lang: str = Field("en", min_length=2, max_length=5)
43
  exaggeration: float = Field(0.5, ge=0.0, le=2.0)
@@ -59,20 +64,47 @@ def tts(req: TTSRequest, request: Request):
59
  exaggeration=req.exaggeration,
60
  cfg_weight=req.cfg_weight,
61
  )
62
- name = f"{uuid.uuid4().hex}.wav"
63
- torchaudio.save(os.path.join(OUT_DIR, name), wav, m.sr)
64
- return {"url": str(request.base_url) + f"audio/{name}", "lang": lang}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
 
67
  @app.get("/audio/{name}")
68
  def download(name: str):
69
  # ponytail: uuid names only; reject anything else instead of path-joining it.
70
- if len(name) != 36 or not name.endswith(".wav") or not name[:32].isalnum():
71
  raise HTTPException(400, "bad name")
72
  path = os.path.join(OUT_DIR, name)
73
  if not os.path.isfile(path):
74
  raise HTTPException(404, "unknown file")
75
- return FileResponse(path, media_type="audio/wav", filename=name)
 
76
 
77
 
78
  @app.get("/")
 
1
  import os
2
+ import re
3
+ import secrets
4
  import uuid
5
 
6
  from fastapi import Depends, FastAPI, HTTPException, Header, Request
7
  from fastapi.responses import FileResponse
8
  from pydantic import BaseModel, Field
9
 
10
+ # strip(): pasted secrets often carry a trailing newline.
11
+ API_KEY = os.environ["API_KEY"].strip()
12
  OUT_DIR = os.environ.get("OUT_DIR", "/tmp/audio")
13
  os.makedirs(OUT_DIR, exist_ok=True)
14
 
 
17
 
18
 
19
  def auth(x_api_key: str = Header(None)):
20
+ if not x_api_key or not secrets.compare_digest(x_api_key.strip(), API_KEY):
21
  raise HTTPException(401, "bad api key")
22
 
23
 
 
41
 
42
 
43
  class TTSRequest(BaseModel):
44
+ # NOTE: upstream generate() hardcodes max_new_tokens=1000 at S3_TOKEN_RATE=25, so
45
+ # audio past ~40s (roughly 600-700 chars) is silently truncated, not errored.
46
  text: str = Field(min_length=1, max_length=1000)
47
  lang: str = Field("en", min_length=2, max_length=5)
48
  exaggeration: float = Field(0.5, ge=0.0, le=2.0)
 
64
  exaggeration=req.exaggeration,
65
  cfg_weight=req.cfg_weight,
66
  )
67
+ stem = uuid.uuid4().hex
68
+ torchaudio.save(os.path.join(OUT_DIR, stem + ".wav"), wav, m.sr)
69
+ with open(os.path.join(OUT_DIR, stem + ".srt"), "w") as f:
70
+ f.write(srt(req.text, wav.shape[-1] / m.sr))
71
+ base = str(request.base_url)
72
+ return {
73
+ "url": base + f"audio/{stem}.wav",
74
+ "srt_url": base + f"audio/{stem}.srt",
75
+ "lang": lang,
76
+ }
77
+
78
+
79
+ def _ts(t):
80
+ ms = round(t * 1000)
81
+ return f"{ms // 3600000:02d}:{ms // 60000 % 60:02d}:{ms // 1000 % 60:02d},{ms % 1000:03d}"
82
+
83
+
84
+ def srt(text, duration):
85
+ # ponytail: chatterbox gives no word timings, so split on sentence enders and
86
+ # give each cue a slice of the duration proportional to its length. Swap in
87
+ # forced alignment (whisperx/aeneas) if the drift ever matters.
88
+ parts = [s.strip() for s in re.split(r"(?<=[.!?。!?])\s+", text) if s.strip()]
89
+ total = sum(len(p) for p in parts) or 1
90
+ out, t = [], 0.0
91
+ for i, p in enumerate(parts, 1):
92
+ end = t + duration * len(p) / total
93
+ out.append(f"{i}\n{_ts(t)} --> {_ts(end)}\n{p}\n")
94
+ t = end
95
+ return "\n".join(out)
96
 
97
 
98
  @app.get("/audio/{name}")
99
  def download(name: str):
100
  # ponytail: uuid names only; reject anything else instead of path-joining it.
101
+ if len(name) != 36 or name[32:] not in (".wav", ".srt") or not name[:32].isalnum():
102
  raise HTTPException(400, "bad name")
103
  path = os.path.join(OUT_DIR, name)
104
  if not os.path.isfile(path):
105
  raise HTTPException(404, "unknown file")
106
+ media = "audio/wav" if name.endswith(".wav") else "application/x-subrip"
107
+ return FileResponse(path, media_type=media, filename=name)
108
 
109
 
110
  @app.get("/")
test_download_name.py CHANGED
@@ -19,8 +19,8 @@ def rejected(name):
19
 
20
 
21
  # a real uuid name passes validation (it 404s for a missing file, not 400)
22
- good = f"{uuid.uuid4().hex}.wav"
23
- assert not rejected(good), good
24
 
25
  for bad in [
26
  "../../etc/passwd",
 
19
 
20
 
21
  # a real uuid name passes validation (it 404s for a missing file, not 400)
22
+ for good in (f"{uuid.uuid4().hex}.wav", f"{uuid.uuid4().hex}.srt"):
23
+ assert not rejected(good), good
24
 
25
  for bad in [
26
  "../../etc/passwd",
test_srt.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runnable check for SRT cue timing: python test_srt.py"""
2
+ import os
3
+
4
+ os.environ.setdefault("API_KEY", "test")
5
+ os.environ.setdefault("OUT_DIR", "/tmp/audio-test")
6
+
7
+ from app import srt
8
+
9
+ out = srt("Hi there. How are you?", 10.0)
10
+ assert out.startswith("1\n00:00:00,000 --> "), out
11
+ assert "--> 00:00:10,000" in out, out # last cue ends at the audio duration
12
+ assert out.count("-->") == 2, out
13
+ assert "Hi there." in out and "How are you?" in out
14
+
15
+ assert srt("", 5.0) == ""
16
+ assert srt("one sentence", 3.0).count("-->") == 1
17
+
18
+ print("ok")