Spaces:
Paused
Paused
| from fastapi import FastAPI, Query | |
| from fastapi.responses import StreamingResponse, JSONResponse | |
| import yt_dlp | |
| app = FastAPI( | |
| title="TikTok Downloader API", | |
| version="1.2" | |
| ) | |
| YDL_OPTS = { | |
| "quiet": True, | |
| "skip_download": True, | |
| "noplaylist": True, | |
| "nocheckcertificate": True, | |
| } | |
| def stream_with_ytdlp(media_url: str, headers: dict, content_type: str): | |
| ydl = yt_dlp.YoutubeDL(YDL_OPTS) | |
| req = yt_dlp.networking.Request(media_url, headers=headers) | |
| res = ydl.urlopen(req) | |
| return StreamingResponse( | |
| res, | |
| media_type=content_type, | |
| headers={ | |
| "Cache-Control": "no-store", | |
| "Accept-Ranges": "bytes" | |
| } | |
| ) | |
| # ================= ROOT ================= | |
| def root(): | |
| return { | |
| "status": True, | |
| "service": "TikTok Downloader API", | |
| "author": "Farel", | |
| "version": "1.2", | |
| "endpoints": { | |
| "mp4": "/api/mp4?url=https://vt.tiktok.com/xxxx/", | |
| "mp3": "/api/mp3?url=https://vt.tiktok.com/xxxx/" | |
| }, | |
| "note": "True streaming via yt-dlp (anti 403)" | |
| } | |
| # ================= MP4 ================== | |
| def mp4(url: str = Query(...)): | |
| try: | |
| with yt_dlp.YoutubeDL(YDL_OPTS) as ydl: | |
| info = ydl.extract_info(url, download=False) | |
| media_url = info.get("url") | |
| headers = info.get("http_headers") | |
| if not media_url or not headers: | |
| raise Exception("Stream data not found") | |
| return stream_with_ytdlp(media_url, headers, "video/mp4") | |
| except Exception as e: | |
| return JSONResponse( | |
| status_code=500, | |
| content={"status": False, "error": str(e)} | |
| ) | |
| # ================= MP3 ================== | |
| def mp3(url: str = Query(...)): | |
| try: | |
| with yt_dlp.YoutubeDL(YDL_OPTS | {"format": "bestaudio"}) as ydl: | |
| info = ydl.extract_info(url, download=False) | |
| media_url = info.get("url") | |
| headers = info.get("http_headers") | |
| if not media_url or not headers: | |
| raise Exception("Stream data not found") | |
| return stream_with_ytdlp(media_url, headers, "audio/mpeg") | |
| except Exception as e: | |
| return JSONResponse( | |
| status_code=500, | |
| content={"status": False, "error": str(e)} | |
| ) |