summaryrefslogtreecommitdiffhomepage
path: root/app/main.py
blob: e91cfffd4c50954571bef5cda09771286c1f3e00 (plain)
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
import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request

from app.schemas import (
    TranscriptFailedResponse,
    TranscriptQueuedResponse,
    TranscriptResponse,
    TranscriptResultResponse,
    TranscriptSegment,
)
from app.storage import TranscriptStore
from app.transcriber import InvalidURLError, create_api, extract_video_id
from app.worker import run_worker

from datetime import datetime

# How long to wait before retrying a failed video, per error_type (seconds).
# All failures are retryable; cooldowns avoid hammering YouTube or a blocked IP.
RETRY_COOLDOWN_SECONDS: dict[str, float] = {
    "not_available": 120.0,        # subtitles may not be generated yet
    "transcript_disabled": 120.0,  # rarely changes, but allow eventual recheck
    "ip_blocked": 120.0,           # back off when our IP is blocked
    "internal_error": 120.0,       # transient bugs / network blips
}
DEFAULT_RETRY_COOLDOWN_SECONDS = 120.0


def _failed_entry_is_retryable(entry: dict) -> bool:
    """Return True if a failed queue entry has cooled down enough to retry."""
    cooldown = RETRY_COOLDOWN_SECONDS.get(
        entry["error_type"] or "", DEFAULT_RETRY_COOLDOWN_SECONDS
    )
    updated_at = entry.get("updated_at")
    if not updated_at:
        return True
    age = (datetime.utcnow() - datetime.fromisoformat(updated_at)).total_seconds()
    return age >= cooldown


@asynccontextmanager
async def lifespan(app: FastAPI):
    store = TranscriptStore("data/transcripts.db")
    await store.initialize()
    api = create_api()
    shutdown_event = asyncio.Event()
    worker_task = asyncio.create_task(run_worker(store, api, shutdown_event))
    app.state.store = store
    try:
        yield
    finally:
        shutdown_event.set()
        worker_task.cancel()
        try:
            await worker_task
        except asyncio.CancelledError:
            pass
        await store.close()


app = FastAPI(
    title="YouTube Transcriber",
    description="API for fetching YouTube video transcripts",
    version="0.2.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/health")
async def health() -> dict[str, str]:
    return {"status": "ok"}


@app.get("/api/transcript", response_model=TranscriptResponse)
async def get_transcript(
    request: Request,
    url: str = Query(..., description="YouTube video URL", min_length=1),
) -> TranscriptResponse:
    try:
        video_id = extract_video_id(url)
    except InvalidURLError:
        raise HTTPException(status_code=400, detail=f"Invalid YouTube URL: {url}")

    store: TranscriptStore = request.app.state.store

    cached = await store.get_transcript(video_id)
    if cached is not None:
        return TranscriptResultResponse(
            video_id=cached["video_id"],
            full_text=cached["full_text"],
            segments=[TranscriptSegment(**s) for s in cached["segments"]],
        )

    entry = await store.get_queue_entry(video_id)
    if entry is not None:
        if entry["status"] == "failed":
            # All failures are retryable once their cooldown has elapsed.
            if _failed_entry_is_retryable(entry):
                await store.requeue_failed(video_id)
                estimate = await store.get_position_and_estimate(video_id)
                return TranscriptQueuedResponse(
                    status="queued",
                    video_id=video_id,
                    position=estimate["position"],
                    estimated_seconds=estimate["estimated_seconds"],
                )
            return TranscriptFailedResponse(
                video_id=video_id,
                error=entry["error"] or "",
                error_type=entry["error_type"] or "",
            )
        # pending or processing
        estimate = await store.get_position_and_estimate(video_id)
        api_status = "processing" if entry["status"] == "processing" else "queued"
        return TranscriptQueuedResponse(
            status=api_status,
            video_id=video_id,
            position=estimate["position"],
            estimated_seconds=estimate["estimated_seconds"],
        )

    # Not cached and not queued — enqueue it.
    await store.enqueue(video_id)
    estimate = await store.get_position_and_estimate(video_id)
    return TranscriptQueuedResponse(
        status="queued",
        video_id=video_id,
        position=estimate["position"],
        estimated_seconds=estimate["estimated_seconds"],
    )