File size: 2,112 Bytes
9be1790
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Dedicated Hugging Face Gradio Space for Levelian YouTube Study Mode Classifier."""
from __future__ import annotations

import os
import time
from pathlib import Path

import gradio as gr
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute

try:
    import spaces  # type: ignore

    @spaces.GPU
    def _zerogpu_probe() -> str:
        return "ok"
except Exception:
    pass

from study_classifier import classify_youtube_study, init_study_cache

CACHE_DB = Path("/tmp/levelian_study_cache.db")
init_study_cache(CACHE_DB)


def _read_env(key: str) -> str:
    return os.environ.get(key, "").strip()


async def health():
    return JSONResponse(
        {
            "ok": True,
            "service": "levelian-study",
            "youtubeApiConfigured": bool(_read_env("YOUTUBE_API_KEY")),
            "groqConfigured": bool(_read_env("GROQ_API_KEY")),
            "geminiConfigured": bool(_read_env("GEMINI_API_KEY")),
        }
    )


async def study_classify(request: Request):
    try:
        body = await request.json()
    except Exception:
        return JSONResponse(status_code=400, content={"ok": False, "error": "INVALID_JSON"})
    res = classify_youtube_study(
        video_id=str(body.get("videoId") or "").strip(),
        title=str(body.get("title") or "").strip(),
        channel=str(body.get("channel") or "").strip(),
        db_path=CACHE_DB,
        env_reader=_read_env,
    )
    return JSONResponse({"ok": True, **res})


with gr.Blocks(title="Levelian Study AI") as demo:
    gr.Markdown(
        "# Levelian YouTube Study Classifier\n"
        "Status: **Live** · Endpoints: `GET /gradio_api/health`, `POST /gradio_api/api/study/classify`"
    )

if __name__ == "__main__":
    demo.launch(prevent_thread_lock=True)
    custom_routes = [
        APIRoute("/gradio_api/health", health, methods=["GET"]),
        APIRoute("/gradio_api/api/study/classify", study_classify, methods=["POST"]),
    ]
    for r in reversed(custom_routes):
        demo.app.router.routes.insert(0, r)
    while True:
        time.sleep(3600)