Spaces:
Running
Running
Upload main.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761"""StreamForge API v3 - Multi-Language Stream ScraperBased on CloudStream extensions + CinePro core providersScrapes direct m3u8 URLs via API endpoints (no browser automation needed)"""
from fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Optionalimport httpximport jsonimport reimport hashlibimport base64import timeimport asynciofrom bs4 import BeautifulSoup
app = FastAPI( title="StreamForge API", description="Multi-language stream scraper - Hindi, Tamil, Telugu, English, Italian, French & more", version="3.0.0",)
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
TMDB_API_KEY = "7967738a03ec215c7d6d675faba9c973"TMDB_BASE = "https://api.themoviedb.org/3"
HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Accept": "application/json", "Accept-Language": "en-US,en;q=0.5",}
# ===== Models =====
class ScrapeRequest(BaseModel): tmdb_id: int media_type: str = "movie" season: Optional[int] = None episode: Optional[int] = None sources: Optional[list[str]] = None
class StreamResult(BaseModel): source: str title: str quality: str language: str url: str type: str
# ===== Helpers =====
async def get_tmdb_info(tmdb_id: int, media_type: str) -> dict: async with httpx.AsyncClient(timeout=10) as client: type_path = "tv" if media_type == "tv" else "movie" resp = await client.get( f"{TMDB_BASE}/{type_path}/{tmdb_id}", params={"api_key": TMDB_API_KEY, "append_to_response": "external_ids"} ) data = resp.json() return { "imdb_id": data.get("external_ids", {}).get("imdb_id"), "title": data.get("title") or data.get("name"), "overview": data.get("overview"), "poster_path": data.get("poster_path"), "original_title": data.get("original_title") or data.get("original_name"), "year": (data.get("release_date") or data.get("first_air_date") or "")[:4], }
def detect_language(label: str) -> str: lower = label.lower() if "hindi" in lower or "hin" in lower: return "Hindi" if "tamil" in lower or "tam" in lower: return "Tamil" if "telugu" in lower or "tel" in lower: return "Telugu" if "bengali" in lower or "bangla" in lower or "ben" in lower: return "Bengali" if "malayalam" in lower or "mal" in lower: return "Malayalam" if "kannada" in lower or "kan" in lower: return "Kannada" if "english" in lower or "eng" in lower or "en" == lower: return "English" if "italian" in lower or "ita" in lower or "italiano" in lower: return "Italian" if "french" in lower or "fra" in lower or "vf" in lower: return "French" if "german" in lower or "deu" in lower or "ger" in lower: return "German" if "spanish" in lower or "spa" in lower or "español" in lower: return "Spanish" if "vietnamese" in lower or "vie" in lower: return "Vietnamese" if "arabic" in lower or "ara" in lower: return "Arabic" if "multi" in lower: return "Multi" return "English" # Default for API-based providers
# ===== CineSu Scraper (Direct m3u8 API - English, some multi-language) =====# Flow: Construct URL → HEAD verify → return m3u8
async def scrape_cinesu(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client: if media_type == "movie": url = f"https://cine.su/v1/stream/master/movie/{tmdb_id}.m3u8" else: s = season or 1 e = episode or 1 url = f"https://cine.su/v1/stream/master/tv/{tmdb_id}/{s}/{e}.m3u8"
resp = await client.get(url, headers={ "Referer": "https://cine.su/en/watch", "Origin": "https://cine.su", })
if resp.status_code == 404: errors.append("CineSu: Content not available") return results, errors
if resp.status_code != 200: errors.append(f"CineSu: HTTP {resp.status_code}") return results, errors
# Parse M3U8 playlist content = resp.text if "#EXT-X-STREAM-INF" in content: lines = content.split("\n") for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) name = re.search(r'NAME="([^"]+)"', line) quality = resolution.group(1) if resolution else "Auto" label = name.group(1) if name else quality if i + 1 < len(lines) and lines[i + 1].startswith("http"): results.append(StreamResult( source="CineSu", title=label, quality=quality, language="English", url=lines[i + 1].strip(), type="m3u8", )) elif ".m3u8" in content: # Direct m3u8 URL m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', content) if m3u8_match: results.append(StreamResult( source="CineSu", title="English Stream", quality="Auto", language="English", url=m3u8_match.group(0), type="m3u8", ))
if not results: errors.append("CineSu: No streams found")
except Exception as e: errors.append(f"CineSu: {str(e)}")
return results, errors
# ===== VixSrc Scraper (Token-based m3u8 - Multi-language audio) =====# Flow: API → embed HTML → extract token → master m3u8 with multi-audio
async def scrape_vixsrc(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: # Step 1: Get embed path if media_type == "movie": api_url = f"https://vixsrc.to/api/movie/{tmdb_id}" else: s = season or 1 e = episode or 1 api_url = f"https://vixsrc.to/api/tv/{tmdb_id}/{s}/{e}"
api_resp = await client.get(api_url) api_data = api_resp.json() src_path = api_data.get("src", "")
if not src_path: errors.append("VixSrc: No embed path returned") return results, errors
# Step 2: Fetch embed HTML embed_resp = await client.get(f"https://vixsrc.to{src_path}") html = embed_resp.text
# Step 3: Extract token, expires, playlist URL token_match = re.search(r'token["\']\s*:\s*["\']([^"\']+)', html) expires_match = re.search(r'expires["\']\s*:\s*["\']([^"\']+)', html) url_match = re.search(r'url\s*:\s*["\']([^"\']+)', html)
if not (token_match and expires_match and url_match): errors.append("VixSrc: Could not extract stream parameters") return results, errors
token = token_match.group(1) expires = expires_match.group(1) playlist = url_match.group(1)
# Step 4: Build master URL sep = "&" if "?" in playlist else "?" master_url = f"{playlist}{sep}token={token}&expires={expires}&h=1"
# Step 5: Fetch master playlist pl_resp = await client.get(master_url, headers={"Referer": f"https://vixsrc.to{src_path}"}) pl_content = pl_resp.text
if "#EXTM3U" in pl_content: # Parse audio tracks audio_tracks = [] lines = pl_content.split("\n") for line in lines: if line.startswith("#EXT-X-MEDIA:TYPE=AUDIO"): lang_match = re.search(r'LANGUAGE="([^"]+)"', line) name_match = re.search(r'NAME="([^"]+)"', line) uri_match = re.search(r'URI="([^"]+)"', line) if lang_match and uri_match: audio_tracks.append({ "language": name_match.group(1) if name_match else lang_match.group(1), "uri": uri_match.group(1), })
# Parse video streams for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): resolution = re.search(r'RESOLUTION=(\d+x\d+)', line) quality = resolution.group(1) if resolution else "Auto" if i + 1 < len(lines) and lines[i + 1].startswith("http"): video_url = lines[i + 1].strip() # Add each audio track as a separate result if audio_tracks: for track in audio_tracks: results.append(StreamResult( source="VixSrc", title=f"{track['language']} Audio", quality=quality, language=detect_language(track["language"]), url=video_url, # Video URL, audio is separate type="m3u8", )) else: results.append(StreamResult( source="VixSrc", title="English Stream", quality=quality, language="English", url=video_url, type="m3u8", )) else: # Direct m3u8 URL results.append(StreamResult( source="VixSrc", title="Stream", quality="Auto", language="English", url=master_url, type="m3u8", ))
if not results: errors.append("VixSrc: No streams found in playlist")
except Exception as e: errors.append(f"VixSrc: {str(e)}")
return results, errors
# ===== VidNest Scraper (Custom base64 - Multi-language including French) =====
VIDNEST_ALPHABET = "RB0fpH8ZEyVLkv7c2i6MAJ5u3IKFDxlS1NTsnGaqmXYdUrtzjwObCgQP94hoeW+/="
def vidnest_b64_decode(input_str: str) -> str: lookup = {c: i for i, c in enumerate(VIDNEST_ALPHABET)} mod = len(input_str) % 4 if mod: input_str += "=" * (4 - mod) result = bytearray() for i in range(0, len(input_str), 4): chunk = input_str[i:i+4] c0 = lookup.get(chunk[0], 64) c1 = lookup.get(chunk[1], 64) c2 = 64 if chunk[2] == "=" else lookup.get(chunk[2], 64) c3 = 64 if chunk[3] == "=" else lookup.get(chunk[3], 64) result.append(((c0 << 2) | (c1 >> 4)) & 0xff) if c2 != 64: result.append((((c1 & 0x0f) << 4) | (c2 >> 2)) & 0xff) if c3 != 64: result.append((((c2 & 0x03) << 6) | c3) & 0xff) return bytes(result).decode("utf-8", errors="ignore")
async def scrape_vidnest(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
# VidNest servers and their languages servers = { "purstream": "French", "klikxxi": "English", "hollymoviehd": "English", "moviebox": "Multi", "allmovies": "Multi", "vidlink": "English", "onehd": "English", "flixhq": "English", }
try: async with httpx.AsyncClient(timeout=10, follow_redirects=True, headers=HEADERS) as client: async def fetch_server(server_name: str, language: str): server_results = [] try: if media_type == "movie": url = f"https://new.vidnest.fun/{server_name}/movie/{tmdb_id}" else: s = season or 1 e = episode or 1 url = f"https://new.vidnest.fun/{server_name}/tv/{tmdb_id}/{s}/{e}"
resp = await client.get(url) if resp.status_code != 200: return server_results, f"{server_name}: HTTP {resp.status_code}"
data = resp.json() encoded_data = data.get("data", "") if not encoded_data: return server_results, f"{server_name}: No data"
decoded = vidnest_b64_decode(encoded_data) parsed = json.loads(decoded)
sources = parsed.get("sources", []) title = parsed.get("title", "")
for source in sources: url_key = None for key in ["url", "file", "stream", "src", "link"]: if key in source: url_key = key break if not url_key: continue
stream_url = source[url_key] quality = source.get("quality") or source.get("label") or source.get("name", "Auto") source_name = source.get("name", source.get("label", "")) stream_type = "m3u8" if ".m3u8" in stream_url or source.get("type") == "hls" else "direct"
# Detect language from source name or server lang = detect_language(source_name) if source_name else language
server_results.append(StreamResult( source=f"VidNest/{server_name}", title=source_name or title, quality=quality, language=lang, url=stream_url, type=stream_type, ))
except Exception as e: return server_results, f"{server_name}: {str(e)}"
return server_results, None
# Fetch all servers in parallel tasks = [fetch_server(name, lang) for name, lang in servers.items()] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"VidNest: {str(result)}") else: server_results, error = result results.extend(server_results) if error: errors.append(f"VidNest {error}")
except Exception as e: errors.append(f"VidNest: {str(e)}")
return results, errors
# ===== Popr Scraper (Aggregator API - Multi-language including Hindi) =====
async def scrape_popr(tmdb_id: int, media_type: str, season: int = None, episode: int = None): results = [] errors = []
servers = ["default", "catflix", "hexa", "Gama", "Liligoon", "Sigma", "Prime", "Alfa", "Lamda"]
try: async with httpx.AsyncClient(timeout=20, follow_redirects=True, headers=HEADERS) as client: async def fetch_server(server: str): server_results = [] try: if media_type == "movie": url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=movie&server={server}" else: s = season or 1 e = episode or 1 url = f"https://popr.ink/api/vidnest?id={tmdb_id}&type=tv&server={server}&season={s}&episode={e}"
resp = await client.get(url) if resp.status_code != 200: return server_results, f"{server}: HTTP {resp.status_code}"
data = resp.json() if not data.get("success"): return server_results, None
for r in data.get("results", []): for stream in r.get("streams", []): stream_url = stream.get("url", "") quality = stream.get("quality", "Auto") is_m3u8 = stream.get("isM3U8", False) stream_type = "m3u8" if is_m3u8 else "direct"
# Detect language from quality label lang = detect_language(quality)
server_results.append(StreamResult( source=f"Popr/{server}", title=quality, quality=quality, language=lang, url=stream_url, type=stream_type, ))
except Exception as e: return server_results, f"{server}: {str(e)}"
return server_results, None
# Fetch servers in parallel tasks = [fetch_server(s) for s in servers] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): errors.append(f"Popr: {str(result)}") else: server_results, error = result results.extend(server_results) if error: errors.append(f"Popr {error}")
# Deduplicate by URL seen_urls = set() unique_results = [] for r in results: if r.url not in seen_urls: seen_urls.add(r.url) unique_results.append(r) results = unique_results
except Exception as e: errors.append(f"Popr: {str(e)}")
return results, errors
# ===== AllMovieLand Scraper (Hindi, Tamil, Telugu, Bengali - CSRF-based) =====
async def scrape_allmovieland(imdb_id: str, media_type: str, season: int = None, episode: int = None): results = [] errors = []
try: async with httpx.AsyncClient(timeout=15, follow_redirects=True, headers=HEADERS) as client: known_domains = ["piexe411qok.com"]
# Discover player domain try: resp = await client.get("https://allmovieland.one/") html = resp.text domains = set(re.findall(r'https?://([a-z0-9]+\.com)', html)) skip = {"google.com", "facebook.com", "youtube.com", "allmovielandapp.com", "bit.ly", "vk.com", "ok.ru", "googletagmanager.com"} for d in domains: if d not in skip: known_domains.insert(0, d) except: pass
# Get PHPSESSID resp0 = await client.get("https://allmovieland.one/") aml_sessid = "" for name, value in resp0.cookies.items(): if name == "PHPSESSID": aml_sessid = value break
if not aml_sessid: errors.append("AllMovieLand: Could not get session") return results, errors
# Find working player domain and get embed player_domain = None embed_html = None for domain in known_domains: try: resp = await client.get( f"https://{domain}/play/{imdb_id}", headers={"Referer": "https://allmovieland.one/"}, ) if "HDVBPlayer" in resp.text or "let p3" in resp.text: player_domain = domain embed_html = resp.text break except: continue
if not player_domain or not embed_html: errors.append("AllMovieLand: Could not load player page") return results, errors
embed_url = f"https://{player_domain}/play/{imdb_id}"
# Parse config and POST for playlist (with CSRF retry) for attempt in range(3): try: # Get fresh embed for CSRF token resp1 = await client.get( f"https://{player_domain}/play/{imdb_id}", headers={"Referer": "https://allmovieland.one/"}, ) html = resp1.text match = re.search(r'let\s+p3\s*=\s*(\{[\s\S]*?\})\s*;', html) if not match: match = re.search(r'new\s+HDVBPlayer\((\{[\s\S]*?\})\)', html) if not match: continue
try: config = json.loads(match.group(1)) except: config = json.loads(match.group(1).replace("\\/", "/"))
key = config.get("key", "") file_url = config.get("file", "").replace("\\/", "/")
# POST immediately with proper headers resp2 = await client.post( file_url, headers={ "X-CSRF-TOKEN": key, "Referer": embed_url, "Cookie": f"PHPSESSID={aml_sessid}", "Content-Type": "application/x-www-form-urlencoded", "Origin": f"https://{player_domain}", } ) content = resp2.text.strip()
if content in ("7", "10", "11"): continue # CSRF expired, retry
playlist = json.loads(content)
# Get m3u8 for each language for item in playlist: lang = item.get("title", "Unknown") file_id = item.get("file", "") playlist_url = f"https://{player_domain}/playlist/{file_id}.txt"
resp3 = await client.post( playlist_url, headers={ "X-CSRF-TOKEN": key, "Referer": embed_url, "Cookie": f"PHPSESSID={aml_sessid}", "Content-Type": "application/x-www-form-urlencoded", "Origin": f"https://{player_domain}", } ) m3u8 = resp3.text.strip()
if m3u8 in ("7", "10", "11"): continue
if m3u8.startswith("#EXTM3U"): lines = m3u8.split("\n") for i, line in enumerate(lines): if line.startswith("#EXT-X-STREAM-INF:"): quality = re.search(r'RESOLUTION=(\d+x\d+)', line) quality_str = quality.group(1) if quality else "Auto" if i + 1 < len(lines) and lines[i + 1].startswith("http"): results.append(StreamResult( source="AllMovieLand", title=lang, quality=quality_str, language=detect_language(lang), url=lines[i + 1].strip(), type="m3u8", )) elif m3u8.startswith("http"): url = m3u8.split("\n")[0].strip() stream_type = "m3u8" if ".m3u8" in url else "direct" results.append(StreamResult( source="AllMovieLand", title=lang, quality="Auto", language=detect_language(lang), url=url, type=stream_type, )) elif ".m3u8" in m3u8: m3u8_match = re.search(r'https?://[^\s"\'<>]+\.m3u8[^\s"\'<>]*', m3u8) if m3u8_match: results.append(StreamResult( source="AllMovieLand", title=lang, quality="Auto", language=detect_language(lang), url=m3u8_match.group(0), type="m3u8", ))
break # Success, stop retrying
except: continue
if not results: errors.append("AllMovieLand: No streams found")
except Exception as e: errors.append(f"AllMovieLand: {str(e)}")
return results, errors
# ===== API Endpoints =====
@app.get("/")async def root(): return { "name": "StreamForge API", "version": "3.0.0", "description": "Multi-language stream scraper - direct m3u8 via API", "endpoints": { "/api/search": "Search TMDB for movies/TV", "/api/scrape": "Scrape streaming links", "/api/sources": "List available sources", "/api/health": "Health check", } }
@app.get("/api/health")async def health(): return {"status": "ok", "timestamp": int(time.time())}
@app.get("/api/sources")async def list_sources(): return { "sources": [ {"name": "CineSu", "language": "English", "langCode": "en", "type": "both", "method": "direct_api"}, {"name": "VixSrc", "language": "Multi", "langCode": "multi", "type": "both", "method": "token_api"}, {"name": "VidNest", "language": "Multi", "langCode": "multi", "type": "both", "method": "custom_b64_api"}, {"name": "Popr", "language": "Multi", "langCode": "multi", "type": "both", "method": "aggregator_api"}, {"name": "AllMovieLand", "language": "Hindi", "langCode": "hi", "type": "both", "method": "csrf_scrape"}, ] }
@app.get("/api/search")async def search_tmdb(q: str = Query(...), page: int = 1): async with httpx.AsyncClient(timeout=10) as client: resp = await client.get( f"{TMDB_BASE}/search/multi", params={"api_key": TMDB_API_KEY, "query": q, "page": page, "include_adult": False} ) data = resp.json() filtered = [r for r in data.get("results", []) if r.get("media_type") in ("movie", "tv")] return { "page": data.get("page"), "total_pages": data.get("total_pages"), "total_results": data.get("total_results"), "results": filtered, }
@app.post("/api/scrape")async def scrape(request: ScrapeRequest): # Get TMDB info try: info = await get_tmdb_info(request.tmdb_id, request.media_type) except Exception as e: raise HTTPException(status_code=500, detail=f"TMDB lookup failed: {str(e)}")
imdb_id = info.get("imdb_id") title = info.get("title")
all_results = [] all_errors = []
# Define all scrapers requested_sources = request.sources or ["CineSu", "VixSrc", "Popr", "AllMovieLand"]
async def run_scraper(name: str, scraper): try: r, e = await asyncio.wait_for(scraper(), timeout=30) return r, e except asyncio.TimeoutError: return [], [f"{name}: Timeout (30s)"] except Exception as ex: return [], [f"{name}: {str(ex)}"]
scraper_map = { "CineSu": lambda: scrape_cinesu(request.tmdb_id, request.media_type, request.season, request.episode), "VixSrc": lambda: scrape_vixsrc(request.tmdb_id, request.media_type, request.season, request.episode), "VidNest": lambda: scrape_vidnest(request.tmdb_id, request.media_type, request.season, request.episode), "Popr": lambda: scrape_popr(request.tmdb_id, request.media_type, request.season, request.episode), "AllMovieLand": lambda: scrape_allmovieland(imdb_id, request.media_type, request.season, request.episode) if imdb_id else ([], ["AllMovieLand: No IMDB ID"]), }
active_scrapers = {k: v for k, v in scraper_map.items() if k in requested_sources}
tasks = [run_scraper(name, scraper) for name, scraper in active_scrapers.items()] task_results = await asyncio.gather(*tasks, return_exceptions=True)
for result in task_results: if isinstance(result, Exception): all_errors.append(f"Scraper failed: {str(result)}") else: r, e = result all_results.extend(r) all_errors.extend(e)
return { "success": len(all_results) > 0, "tmdb_id": request.tmdb_id, "title": title, "imdb_id": imdb_id, "results": [r.dict() for r in all_results], "errors": all_errors, }
@app.post("/api/scrape/all")async def scrape_all(request: ScrapeRequest): """Scrape from ALL available sources""" request.sources = ["CineSu", "VixSrc", "VidNest", "Popr", "AllMovieLand"] return await scrape(request)
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)main.pyAdded+761