File size: 12,870 Bytes
5b7cd5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3edeefe
5b7cd5f
 
 
3edeefe
5b7cd5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12ab2ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b7cd5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3edeefe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b7cd5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"""
APIRouter for /api/tools/* endpoints.

Each endpoint is sync request-response (no SSE, no job state). Input files
land in a fresh per-run directory, outputs are returned as a download URL
to GET /api/tools/file/{run_id}/{filename}.
"""
from __future__ import annotations

import asyncio
from pathlib import Path
from typing import Optional

from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse
from pydantic import BaseModel

from server import limiter, _download_url, _is_allowed_video_host

from . import audio_cleanup, dramabox, scene_writer, subtitles, voice_clone
from .storage import (
    file_url,
    new_run_dir,
    reap_old_runs,
    run_dir,
    safe_filename,
)

router = APIRouter(prefix="/api/tools", tags=["tools"])

# Per-tool body size cap (separate from pipeline's MAX_UPLOAD_BYTES check).
TOOLS_MAX_BYTES = 50 * 1024 * 1024  # 50 MB


# ── Helpers ──────────────────────────────────────────────────────────

async def _save_upload(file: UploadFile, dest_dir: Path, default_name: str) -> Path:
    """Stream upload to disk, enforcing the tools size cap."""
    dest = dest_dir / safe_filename(file.filename, default_name)
    written = 0
    with open(dest, "wb") as fh:
        while chunk := await file.read(1024 * 1024):
            written += len(chunk)
            if written > TOOLS_MAX_BYTES:
                fh.close()
                dest.unlink(missing_ok=True)
                raise HTTPException(413, f"File too large (max {TOOLS_MAX_BYTES // (1024*1024)} MB).")
            fh.write(chunk)
    return dest


def _ext_to_media_type(filename: str) -> str:
    ext = Path(filename).suffix.lower()
    return {
        ".mp4": "video/mp4",
        ".mov": "video/quicktime",
        ".webm": "video/webm",
        ".mp3": "audio/mpeg",
        ".wav": "audio/wav",
        ".srt": "application/x-subrip",
        ".vtt": "text/vtt",
        ".txt": "text/plain",
    }.get(ext, "application/octet-stream")


# ── Subtitles ────────────────────────────────────────────────────────

@router.post("/subtitles")
@limiter.limit("10/hour")
async def subtitles_endpoint(
    request: Request,
    file: Optional[UploadFile] = File(None),
    url: Optional[str] = Form(None),
    source_lang: str = Form("Auto-detect"),
    target_lang: str = Form("Same as source"),
    fmt: str = Form("srt"),
    style: str = Form("tiktok"),
    position: str = Form("bottom"),
    h_align: str = Form("center"),
    font_size: Optional[int] = Form(None),
    margin_v: Optional[int] = Form(None),
):
    if fmt not in ("srt", "vtt", "txt", "mp4"):
        raise HTTPException(400, "fmt must be one of: srt, vtt, txt, mp4")
    if style not in ("tiktok", "youtube", "minimal"):
        raise HTTPException(400, "style must be one of: tiktok, youtube, minimal")
    if position not in ("top", "middle", "bottom"):
        raise HTTPException(400, "position must be one of: top, middle, bottom")
    if h_align not in ("left", "center", "right"):
        raise HTTPException(400, "h_align must be one of: left, center, right")

    url = (url or "").strip()
    if not file and not url:
        raise HTTPException(400, "Provide either a file upload or a video URL.")
    if file and url:
        raise HTTPException(400, "Send a file OR a URL, not both.")

    run_id, dest_dir = new_run_dir()
    if file:
        input_path = await _save_upload(file, dest_dir, "input.mp4")
    else:
        if not _is_allowed_video_host(url):
            raise HTTPException(400, "URL host not supported. Use TikTok, YouTube, or Instagram.")
        input_path = Path(dest_dir) / "input.mp4"
        try:
            await asyncio.to_thread(_download_url, url, str(input_path))
        except Exception as e:  # noqa: BLE001
            raise HTTPException(400, f"Couldn't fetch the video URL: {e}")

    try:
        # Heavy: transcribe + (optional) translate + (optional) ffmpeg burn-in.
        # Run off the event loop so concurrent requests don't starve.
        info = await asyncio.to_thread(
            subtitles.generate_subtitles,
            input_path=input_path,
            out_dir=dest_dir,
            source_lang_name=source_lang,
            target_lang_name=target_lang,
            fmt=fmt,  # type: ignore[arg-type]
            style=style,  # type: ignore[arg-type]
            position=position,  # type: ignore[arg-type]
            h_align=h_align,  # type: ignore[arg-type]
            font_size=font_size,
            margin_v=margin_v,
        )
    except ValueError as e:
        raise HTTPException(400, str(e))
    except Exception as e:  # noqa: BLE001
        raise HTTPException(500, f"Subtitle generation failed: {e}")

    return JSONResponse({
        "run_id": run_id,
        "format": info["format"],
        "filename": info["filename"],
        "url": file_url(run_id, info["filename"]),
        "segments": info["segments"],
        "translated": info["translated"],
    })


# ── Voice clone ──────────────────────────────────────────────────────

@router.post("/voice-clone")
@limiter.limit("10/hour")
async def voice_clone_endpoint(
    request: Request,
    sample: UploadFile = File(...),
    text: str = Form(...),
    language_id: str = Form("en"),
):
    text = (text or "").strip()
    if not text:
        raise HTTPException(400, "text is required")
    if len(text) > 1000:
        raise HTTPException(400, "text exceeds 1000 char limit")

    run_id, dest_dir = new_run_dir()
    sample_path = await _save_upload(sample, dest_dir, "sample.wav")

    try:
        info = await asyncio.to_thread(
            voice_clone.clone_voice,
            sample_path=sample_path,
            text=text,
            out_dir=dest_dir,
            language_id=language_id,
        )
    except ValueError as e:
        raise HTTPException(400, str(e))
    except Exception as e:  # noqa: BLE001
        raise HTTPException(500, f"Voice clone failed: {e}")

    return JSONResponse({
        "run_id": run_id,
        "engine": info["engine"],
        "chunks": info["chunks"],
        "filename": info["filename"],
        "url": file_url(run_id, info["filename"]),
    })


# ── Dramabox ─────────────────────────────────────────────────────────

@router.post("/dramabox")
@limiter.limit("10/hour")
async def dramabox_endpoint(
    request: Request,
    prompt: str = Form(...),
    audio_ref: Optional[UploadFile] = File(None),
    cfg: float = Form(2.5),
    stg: float = Form(1.5),
    dur_mult: float = Form(1.1),
    gen_dur: float = Form(0.0),
    ref_dur: float = Form(10.0),
    seed: int = Form(42),
):
    prompt = (prompt or "").strip()
    if not prompt:
        raise HTTPException(400, "prompt is required")
    if len(prompt) > 2000:
        raise HTTPException(400, "prompt exceeds 2000 char limit")

    # Range guards mirror the upstream Dramabox sliders.
    if not (1.0 <= cfg <= 10.0):
        raise HTTPException(400, "cfg must be between 1 and 10")
    if not (0.0 <= stg <= 5.0):
        raise HTTPException(400, "stg must be between 0 and 5")
    if not (0.8 <= dur_mult <= 2.0):
        raise HTTPException(400, "dur_mult must be between 0.8 and 2.0")
    if not (0.0 <= gen_dur <= 60.0):
        raise HTTPException(400, "gen_dur must be between 0 and 60")
    if not (3.0 <= ref_dur <= 30.0):
        raise HTTPException(400, "ref_dur must be between 3 and 30")

    run_id, dest_dir = new_run_dir()

    ref_path: Optional[Path] = None
    if audio_ref is not None and audio_ref.filename:
        ref_path = await _save_upload(audio_ref, dest_dir, "voice_ref.wav")

    try:
        info = await asyncio.to_thread(
            dramabox.generate_scene,
            prompt=prompt,
            out_dir=dest_dir,
            audio_ref=ref_path,
            cfg=cfg,
            stg=stg,
            dur_mult=dur_mult,
            gen_dur=gen_dur,
            ref_dur=ref_dur,
            seed=seed,
        )
    except ValueError as e:
        raise HTTPException(400, str(e))
    except RuntimeError as e:
        # Raised by dramabox._ensure_server() on Spaces that don't ship the
        # vendored model. Surface clearly so the frontend can fall back.
        raise HTTPException(503, str(e))
    except Exception as e:  # noqa: BLE001
        raise HTTPException(500, f"Dramabox generation failed: {e}")

    return JSONResponse({
        "run_id": run_id,
        "filename": info["filename"],
        "url": file_url(run_id, info["filename"]),
        "elapsed": info["elapsed"],
        "settings": info["settings"],
    })


# ── Audio cleanup ────────────────────────────────────────────────────

@router.post("/audio-cleanup")
@limiter.limit("10/hour")
async def audio_cleanup_endpoint(
    request: Request,
    file: UploadFile = File(...),
    mode: str = Form("vocals-only"),
):
    if mode not in ("vocals-only", "instrumental-only", "stems"):
        raise HTTPException(400, "mode must be one of: vocals-only, instrumental-only, stems")

    run_id, dest_dir = new_run_dir()
    input_path = await _save_upload(file, dest_dir, "input.wav")

    try:
        stems = await asyncio.to_thread(
            audio_cleanup.separate,
            input_path=input_path,
            out_dir=dest_dir,
            mode=mode,  # type: ignore[arg-type]
        )
    except ValueError as e:
        raise HTTPException(400, str(e))
    except Exception as e:  # noqa: BLE001
        raise HTTPException(500, f"Audio separation failed: {e}")

    return JSONResponse({
        "run_id": run_id,
        "mode": mode,
        "stems": [
            {**stem, "url": file_url(run_id, stem["filename"])}
            for stem in stems
        ],
    })


# ── Scene writer ─────────────────────────────────────────────────────

class SceneRequest(BaseModel):
    hook_pattern: str
    hook_title: str = ""
    register: str = ""
    register_label: str = ""
    niche: str


@router.post("/scene")
@limiter.limit("30/hour")
async def scene_endpoint(request: Request, body: SceneRequest):
    """Draft a directed DramaBox scene from a viral hook + the creator's niche."""
    niche = body.niche.strip()
    hook_pattern = body.hook_pattern.strip()
    if not niche:
        raise HTTPException(400, "niche is required")
    if not hook_pattern:
        raise HTTPException(400, "hook_pattern is required")
    if len(niche) > 400:
        raise HTTPException(400, "niche exceeds 400 char limit")

    try:
        scene = await asyncio.to_thread(
            scene_writer.write_scene,
            hook_pattern=hook_pattern,
            hook_title=body.hook_title.strip(),
            register=body.register.strip(),
            register_label=body.register_label.strip(),
            niche=niche,
        )
    except Exception as e:  # noqa: BLE001
        raise HTTPException(500, f"Scene generation failed: {e}")

    return JSONResponse({"scene": scene})


# ── File download ────────────────────────────────────────────────────

@router.get("/file/{run_id}/{filename}")
async def tools_file(run_id: str, filename: str):
    """Serve a generated artifact. Run dirs auto-expire after RUN_TTL_SECONDS."""
    safe_name = safe_filename(filename)
    if safe_name != filename:
        raise HTTPException(400, "Invalid filename")

    base = run_dir(run_id)
    if base is None:
        raise HTTPException(404, "Run not found or expired")

    target = base / safe_name
    if not target.exists() or not target.is_file():
        raise HTTPException(404, "File not found")

    return FileResponse(
        path=str(target),
        media_type=_ext_to_media_type(safe_name),
        filename=safe_name,
    )


# ── Cleanup hook ─────────────────────────────────────────────────────

@router.post("/_internal/reap")
async def _reap():
    """Manual reap trigger (mostly for testing). Auto-reap runs on a timer."""
    removed = await asyncio.to_thread(reap_old_runs)
    return {"removed": removed}