File size: 3,547 Bytes
bda305f
 
 
00b0434
162cf59
00b0434
fcaa56a
162cf59
40dbb61
00b0434
162cf59
1ab78e2
7d6be93
f1332f7
aa1867f
00b0434
600705a
ac94e8d
00b0434
162cf59
 
 
 
 
f89dbd6
ac94e8d
 
 
 
 
 
600705a
162cf59
f89dbd6
162cf59
40dbb61
 
 
 
 
162cf59
 
 
 
 
 
 
 
 
 
1ab78e2
7d6be93
bc6734b
f1332f7
aa1867f
162cf59
a2a8ba3
 
75182b8
40dbb61
 
162cf59
 
00b0434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8813304
 
00b0434
 
 
 
 
 
 
 
f89dbd6
00b0434
 
 
 
 
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
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["TRANSFORMERS_NO_ADAPT_TOKENIZER"] = "1"
from datetime import datetime
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from src.api.auth_routes import router as auth_router
from src.api.notes_routes import router as notes_router
from src.api.recommendation_routes import router as recommendation_router
from src.api.analytics_routes import router as analytics_router
from src.api.chat_routes import router as chat_router
from src.api.tts_routes import router as tts_router
from src.utils.logger import setup_logger
from src.utils.model_loader import preload_all_models
from src.utils.config import settings

logger = setup_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("πŸš€ AIdea API starting up...")
    logger.info(
        "πŸ”§ Inference mode: %s | Model: %s",
        settings.inference_mode.upper(),
        settings.groq_model if settings.inference_mode == "groq" else "Qwen2.5-0.5B-Instruct (local)",
    )
    # ── Eager-load AI models (or Groq client) ONCE at startup ──
    preload_all_models()
    yield
    logger.info("πŸ›‘ AIdea API shutting down...")

app = FastAPI(
    title="AIdea API", 
    description="YouTube Study Notes Generation Engine",
    lifespan=lifespan
)

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

app.include_router(notes_router)
app.include_router(recommendation_router)
app.include_router(analytics_router)
app.include_router(auth_router)
app.include_router(chat_router)
app.include_router(tts_router)

@app.get("/")
def read_root():
    return {
        "status": "online",
        "message": "Welcome to AIdea API! Everything is working perfectly.",
    }

@app.get("/health")
async def health_check():
    import socket
    import httpx
    try:
        import dns.resolver
        has_dnspython = True
    except ImportError:
        has_dnspython = False
    
    dns_results = {}
    for domain in ["www.youtube.com", "google.com"]:
        try:
            dns_results[f"{domain}_sys"] = socket.gethostbyname(domain)
        except Exception as e:
            dns_results[f"{domain}_sys"] = f"Error: {e}"
            
        if has_dnspython:
            try:
                resolver = dns.resolver.Resolver()
                resolver.nameservers = ['8.8.8.8']
                answer = resolver.resolve(domain, 'A')
                dns_results[f"{domain}_ext"] = [str(rdata) for rdata in answer]
            except Exception as e:
                dns_results[f"{domain}_ext"] = f"Error: {repr(e)}"
        else:
            dns_results[f"{domain}_ext"] = "dnspython not installed"
            
    connectivity = {}
    proxy_url = os.environ.get("PROXY_URL", "").strip() or os.environ.get("YOUTUBE_PROXY", "").strip()
    async with httpx.AsyncClient(timeout=5.0, proxy=proxy_url or None) as client:
        for url in ["https://www.youtube.com"]:
            try:
                resp = await client.get(url, follow_redirects=True)
                connectivity[url] = f"OK ({resp.status_code})"
            except Exception as e:
                connectivity[url] = f"Failed: {repr(e)}"
                
    return {
        "status": "v7-supadata-only",
        "dnspython": has_dnspython,
        "dns": dns_results,
        "connectivity": connectivity,
        "timestamp": datetime.now()
    }