File size: 10,249 Bytes
83a7dad
4b5adfb
 
 
8813304
81618af
4b5adfb
d74863e
9201bb0
4b5adfb
 
d74863e
81618af
4b5adfb
 
81618af
4b5adfb
 
d74863e
81618af
f0e746a
d74863e
81618af
 
226ed2d
bd357e4
 
 
 
 
8813304
 
 
 
 
 
 
 
 
 
b27b1ac
 
4b5adfb
 
 
 
b27b1ac
9201bb0
b27b1ac
 
 
4b5adfb
b27b1ac
 
9201bb0
b27b1ac
 
cbed3ed
4b5adfb
9201bb0
cbed3ed
9201bb0
8813304
4b5adfb
cbed3ed
 
 
 
 
 
 
 
 
 
 
4b5adfb
 
b27b1ac
 
 
 
9201bb0
4b5adfb
83a7dad
 
 
 
 
 
 
 
 
 
 
 
 
 
5985dfd
83a7dad
cbed3ed
 
 
 
9201bb0
8813304
cbed3ed
 
 
4b5adfb
 
226ed2d
 
4b5adfb
 
 
 
83a7dad
 
4b5adfb
 
 
 
83a7dad
 
4b5adfb
83a7dad
 
 
 
4b5adfb
83a7dad
4b5adfb
83a7dad
 
 
4b5adfb
83a7dad
4b5adfb
 
b27b1ac
 
 
 
4b5adfb
 
 
6aee0d2
4b5adfb
9201bb0
b27b1ac
9201bb0
4b5adfb
 
 
0f56eef
 
4b5adfb
 
6aee0d2
0f56eef
 
 
b27b1ac
4b5adfb
83a7dad
 
4b5adfb
81618af
 
 
 
4b5adfb
81618af
 
 
 
d74863e
4b5adfb
d74863e
 
 
 
 
 
 
81618af
 
 
 
 
 
 
 
 
 
 
286c39a
81618af
 
 
 
d74863e
81618af
 
 
 
 
4b5adfb
81618af
d74863e
81618af
 
 
4b5adfb
81618af
d74863e
4b5adfb
81618af
 
 
 
 
d74863e
 
5ed3580
 
 
 
 
 
81618af
4b5adfb
81618af
4b5adfb
81618af
bd357e4
 
 
9201bb0
4b5adfb
bd357e4
 
 
 
 
9201bb0
30a4631
8813304
30a4631
8813304
bd357e4
30a4631
 
 
286c39a
bd357e4
 
 
 
 
 
 
 
 
 
 
81618af
 
6aee0d2
 
 
4b5adfb
 
 
 
226ed2d
81618af
3c66ec8
6aee0d2
81618af
226ed2d
c9146f3
81618af
 
fcaa56a
4b5adfb
 
 
 
 
fcaa56a
9e589ba
4b5adfb
bd357e4
 
 
 
 
fcaa56a
9f6836e
fcaa56a
bd357e4
81618af
9f6836e
 
fcaa56a
6aee0d2
4b5adfb
 
 
 
81618af
4b5adfb
 
bd357e4
 
 
d74863e
 
 
 
4b5adfb
 
d74863e
 
81618af
4b5adfb
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import re
import uuid
import asyncio
from datetime import datetime
from typing import Dict, List

from curl_cffi import requests as curl_requests
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, HttpUrl

from src.api.downloader import YouTubeDownloader
from src.auth.dependencies import get_current_user
from src.db.models import User
from src.summarization.note_generator import NoteGenerator
from src.utils.config import settings
from src.utils.logger import setup_logger

logger = setup_logger(__name__)
router = APIRouter(tags=["Notes"])

tasks: Dict[str, Dict] = {}


def _set_task_status(task_id: str, status: str, message: str) -> None:
    tasks[task_id]["status"] = status
    tasks[task_id]["message"] = message


def _proxy_dict() -> dict | None:
    proxy_url = os.environ.get("PROXY_URL", "").strip() or os.environ.get("YOUTUBE_PROXY", "").strip()
    if not proxy_url:
        return None
    return {
        "http": proxy_url,
        "https": proxy_url,
    }


def _extract_video_id(url: str) -> str:
    """Extract the 11-character YouTube video ID from any URL format."""
    match = re.search(r"(?:v=|youtu\.be/|shorts/|embed/)([A-Za-z0-9_-]{11})", str(url))
    return match.group(1) if match else ""


def _duration_via_supadata(video_id: str) -> int:
    """Estimate video duration from Supadata transcript segment timestamps."""
    api_key = os.environ.get("SUPADATA_API_KEY", "").strip()
    if not api_key:
        return 0

    try:
        api_url = (
            "https://api.supadata.ai/v1/youtube/transcript"
            f"?url=https://www.youtube.com/watch?v={video_id}"
        )
        resp = curl_requests.get(
            api_url,
            headers={"x-api-key": api_key},
            impersonate="chrome124",
            timeout=20,
            proxies=_proxy_dict(),
        )
        resp.raise_for_status()
        data = resp.json()
        segments = data.get("segments") or data.get("content", [])
        if isinstance(segments, list) and segments:
            last = segments[-1]
            offset_ms = last.get("offset", 0) or last.get("start", 0)
            dur_ms = last.get("duration", 0) or last.get("dur", 0)
            total_s = (int(offset_ms) + int(dur_ms)) // 1000
            if total_s > 0:
                logger.info("[S2-supadata] duration~%ds", total_s)
                return total_s
    except Exception as exc:
        logger.warning("[S2-supadata] failed: %s", exc)
    return 0


def _duration_via_html_scrape(url: str) -> int:
    """Scrape the watch page and parse duration hints."""
    headers = {
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/124.0.0.0 Safari/537.36"
        ),
        "Accept-Language": "en-US,en;q=0.9",
        "Accept": (
            "text/html,application/xhtml+xml,application/xml;"
            "q=0.9,image/avif,image/webp,*/*;q=0.8"
        ),
        "Connection": "keep-alive",
        "DNT": "1",
        "Upgrade-Insecure-Requests": "1",
    }

    try:
        resp = curl_requests.get(
            url,
            headers=headers,
            impersonate="chrome124",
            timeout=15,
            proxies=_proxy_dict(),
        )
        resp.raise_for_status()
        html = resp.text
    except Exception as exc:
        logger.warning("[S3-scrape] HTTP fetch failed: %s", exc)
        return 0

    match = re.search(r'"lengthSeconds"\s*:\s*"(\d+)"', html)
    if match:
        duration = int(match.group(1))
        logger.info("[S3a-regex-quoted] duration=%ds", duration)
        return duration

    match = re.search(r'"approxDurationMs"\s*:\s*"(\d+)"', html)
    if match:
        duration = int(match.group(1)) // 1000
        logger.info("[S3b-approxMs] duration=%ds", duration)
        return duration

    match = re.search(
        r"var\s+ytInitialPlayerResponse\s*=\s*(\{.*?\})\s*;",
        html,
        re.DOTALL,
    )
    if match:
        try:
            data = json.loads(match.group(1))
            seconds_str = data.get("videoDetails", {}).get("lengthSeconds", "")
            if seconds_str and str(seconds_str).isdigit():
                duration = int(seconds_str)
                logger.info("[S3c-jsonParse] duration=%ds", duration)
                return duration
        except (json.JSONDecodeError, AttributeError) as exc:
            logger.warning("[S3c-jsonParse] JSON decode failed: %s", exc)

    return 0


def get_youtube_duration(
    url: str,
    preferred_duration: int = 0,
    strategy: str | None = None,
) -> int:
    """Fetch YouTube duration in seconds using Supadata, then page scraping."""
    video_id = _extract_video_id(url)

    if preferred_duration > 0:
        return preferred_duration

    if video_id:
        duration = _duration_via_supadata(video_id)
        if duration > 0:
            return duration

    duration = _duration_via_html_scrape(url)
    if duration > 0:
        return duration

    logger.warning("[duration] All strategies exhausted for: %s", url)
    return 0


class GenerateNotesRequest(BaseModel):
    youtube_url: HttpUrl
    language: str = "en"


class TaskResponse(BaseModel):
    task_id: str
    status: str
    message: str


class GeneratedNoteFile(BaseModel):
    filename: str
    title: str
    created_at: float
    size: int


@router.post("/generate", response_model=TaskResponse)
async def generate_note(
    request: GenerateNotesRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_user),
):
    task_id = str(uuid.uuid4())
    user_id = current_user.id

    tasks[task_id] = {
        "status": "pending",
        "message": "Initializing...",
        "youtube_url": str(request.youtube_url),
        "user_id": user_id,
        "created_at": datetime.now(),
    }

    background_tasks.add_task(
        process_video_task,
        task_id,
        str(request.youtube_url),
        request.language,
        user_id,
    )

    return TaskResponse(
        task_id=task_id,
        status="pending",
        message="Generation started successfully.",
    )


@router.get("/status/{task_id}")
async def get_task_status(task_id: str):
    if task_id not in tasks:
        raise HTTPException(status_code=404, detail="Task not found")
    return tasks[task_id]


async def process_video_task(
    task_id: str,
    youtube_url: str,
    language: str,
    user_id: str,
):
    downloader = YouTubeDownloader()

    try:
        video_id = _extract_video_id(youtube_url)
        video_title = "YouTube Video"

        _set_task_status(task_id, "validating_url", "Validating video URL...")

        prefetched_duration = _duration_via_html_scrape(youtube_url)

        _set_task_status(
            task_id,
            "extracting_content",
            "Checking for available subtitles...",
        )

        try:
            transcript_text = await asyncio.to_thread(
                downloader.get_transcript,
                youtube_url,
            )
        except Exception as transcript_exc:
            logger.info("Subtitle transcript unavailable for task %s: %s", task_id, transcript_exc)
            raise RuntimeError("This video does not have subtitles (CC). Cannot generate notes.")

        _set_task_status(
            task_id,
            "transcript_ready",
            "Transcript ready. Preparing summary...",
        )

        _set_task_status(
            task_id,
            "ai_processing",
            "Generating intelligent summary...",
        )
        note_gen = NoteGenerator()
        summary_json = note_gen.generateSummary(transcript_text, video_title)
        resolved_video_title = video_title
        if resolved_video_title == "YouTube Video":
            resolved_video_title = str(summary_json.get("title") or resolved_video_title)
        video_duration = get_youtube_duration(
            youtube_url,
            preferred_duration=prefetched_duration,
        )

        final_markdown = note_gen.format_final_notes(
            note_gen.format_notes_to_markdown(summary_json),
            resolved_video_title,
            youtube_url,
            video_duration,
            detected_language=summary_json.get("detected_language", "English"),
        )

        segments = summary_json.get("segments", [])
        key_points_list = [
            seg["key_insight"]
            for seg in segments
            if isinstance(seg, dict) and seg.get("key_insight")
        ]

        from src.categorization.topic_classifier import classify_topics

        _set_task_status(
            task_id,
            "structuring_notes",
            "Structuring notes and key points...",
        )
        raw_topics = summary_json.get("topics", [])
        categories = classify_topics(raw_topics) if raw_topics else ["Education & Science"]

        _set_task_status(task_id, "complete", "Generation completed successfully.")
        tasks[task_id]["notes"] = final_markdown
        tasks[task_id]["topics"] = categories
        tasks[task_id]["category"] = categories
        tasks[task_id]["keyPoints"] = key_points_list
        tasks[task_id]["videoTitle"] = resolved_video_title
        tasks[task_id]["thumbnail"] = (
            f"https://img.youtube.com/vi/{video_id}/mqdefault.jpg" if video_id else ""
        )
        logger.info("Task %s completed successfully", task_id)

    except Exception as exc:
        logger.error("Task %s failed: %s", task_id, exc)
        _set_task_status(task_id, "failed", str(exc))


@router.get("/generated", response_model=List[GeneratedNoteFile])
async def list_generated_notes():
    notes = []
    output_dir = settings.output_dir
    if not output_dir.exists():
        return []

    for file_path in output_dir.glob("*_notes.md"):
        stats = file_path.stat()
        notes.append(
            GeneratedNoteFile(
                filename=file_path.name,
                title=file_path.name.replace("_notes.md", ""),
                created_at=stats.st_mtime,
                size=stats.st_size,
            )
        )

    notes.sort(key=lambda item: item.created_at, reverse=True)
    return notes