Upload app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507import asyncioimport osimport reimport urllib.parsefrom typing import Dict, Optional, Tuple
import gradio as grimport httpximport uvicornfrom fastapi import FastAPI, Request, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, StreamingResponse
PORT = int( os.environ.get("GRADIO_SERVER_PORT") or os.environ.get("PORT") or "7860")
try: import spaces
@spaces.GPU def _sf_gpu_ready(): return "ok"except Exception: pass
FIXED_UA = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/125.0.0.0 Safari/537.36")
TESTWAVE_ORIGIN_HOSTS = [ "amorphous-cheetah-ejv65cqsx5x8j7xip061qmst.herokudns.com", "75.2.43.161", "99.83.217.1", "15.197.129.158", "76.223.11.49",]
CORS_HEADERS = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS", "Access-Control-Allow-Headers": "*", "Access-Control-Expose-Headers": "*",}
PASS_HEADERS = ( "content-type", "content-length", "content-range", "accept-ranges", "last-modified", "etag",)
def get_public_base_origin(request: Request) -> str: fwd_host = request.headers.get("x-forwarded-host", "").split(",")[0].strip() host = fwd_host or request.headers.get("host", "").split(",")[0].strip() if not host: return "" fwd_proto = request.headers.get("x-forwarded-proto", "").split(",")[0].strip() if not fwd_proto: fwd_proto = ( "http" if host.startswith("localhost") or host.startswith("127.0.0.1") else "https" ) return f"{fwd_proto}://{host}"
def is_testwave_host(hostname: str) -> bool: h = (hostname or "").lower() return h == "testwave.cc" or h.endswith(".testwave.cc")
def parse_raw_http_headers(header_bytes: bytes) -> Tuple[int, Dict[str, str]]: text = header_bytes.decode("latin-1", errors="replace") lines = text.split("\r\n") status = 502 if lines: m = re.match(r"^HTTP/\d\.\d\s+(\d{3})", lines[0]) if m: status = int(m.group(1)) headers: Dict[str, str] = {} for line in lines[1:]: if ":" in line: k, v = line.split(":", 1) key = k.strip().lower() val = v.strip() if key: headers[key] = val return status, headers
async def open_testwave_tcp( raw_url: str, method: str, range_header: Optional[str], redirect_depth: int = 0,) -> Optional[ Tuple[int, Dict[str, str], bytes, asyncio.StreamReader, asyncio.StreamWriter]]: parsed = urllib.parse.urlsplit(raw_url) target_host = parsed.netloc path_with_query = (parsed.path or "/") + (f"?{parsed.query}" if parsed.query else "")
req_lines = [ f"{'HEAD' if method == 'HEAD' else 'GET'} {path_with_query} HTTP/1.0", f"Host: {target_host}", "Referer: https://stream.aryavidya.cc/", "Connection: close", ] if range_header: req_lines.append(f"Range: {range_header}") raw_req = ("\r\n".join(req_lines) + "\r\n\r\n").encode("latin-1")
for origin_host in TESTWAVE_ORIGIN_HOSTS: writer: Optional[asyncio.StreamWriter] = None try: reader, writer = await asyncio.wait_for( asyncio.open_connection(origin_host, 80), timeout=12.0 ) writer.write(raw_req) await writer.drain()
buf = bytearray() sep_idx = -1 while sep_idx == -1: chunk = await asyncio.wait_for(reader.read(8192), timeout=15.0) if not chunk: break buf.extend(chunk) sep_idx = buf.find(b"\r\n\r\n") if len(buf) > 32768 and sep_idx == -1: break
if sep_idx == -1: writer.close() continue
status, headers = parse_raw_http_headers(bytes(buf[:sep_idx])) leftover = bytes(buf[sep_idx + 4 :])
if ( status in (301, 302, 303, 307, 308) and headers.get("location") and redirect_depth < 3 ): next_url = urllib.parse.urljoin(raw_url, headers["location"]) writer.close() return await open_testwave_tcp( next_url, method, range_header, redirect_depth + 1 )
if status in (200, 206): return status, headers, leftover, reader, writer
writer.close() except Exception: if writer is not None: try: writer.close() except Exception: pass return None
def rewrite_hls_playlist(text: str, raw_url: str, proxy_prefix: str) -> str: parent_parsed = urllib.parse.urlsplit(raw_url) parent_qs = urllib.parse.parse_qsl(parent_parsed.query, keep_blank_values=True)
def merge_and_proxy(target_str: str) -> str: try: abs_target = urllib.parse.urljoin(raw_url, target_str) seg_parsed = urllib.parse.urlsplit(abs_target) seg_params = urllib.parse.parse_qsl(seg_parsed.query, keep_blank_values=True) existing_keys = {k for k, _ in seg_params} for pk, pv in parent_qs: if pk.lower() != "start" and pk not in existing_keys: seg_params.append((pk, pv)) new_query = urllib.parse.urlencode(seg_params) final_seg = urllib.parse.urlunsplit( ( seg_parsed.scheme, seg_parsed.netloc, seg_parsed.path, new_query, seg_parsed.fragment, ) ) return f"{proxy_prefix}?url={urllib.parse.quote(final_seg, safe='')}" except Exception: return target_str
out_lines = [] for line in text.split("\n"): trimmed = line.strip() if not trimmed: out_lines.append(line) continue if trimmed.startswith("#"): if 'URI="' in trimmed: out_lines.append( re.sub( r'URI="([^"]+)"', lambda m: f'URI="{merge_and_proxy(m.group(1))}"', line, ) ) else: out_lines.append(line) continue out_lines.append(merge_and_proxy(trimmed))
result = "\n".join(out_lines) if "#EXT-X-ENDLIST" not in result: result += "\n#EXT-X-ENDLIST\n" return result
app = FastAPI(title="Study Farm Stream Edge")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "HEAD", "OPTIONS"], allow_headers=["*"], expose_headers=["*"],)
@app.get("/health")async def health(): return JSONResponse( { "status": "ok", "service": "study-farm-stream-edge", "endpoints": ["/api/stream-proxy?url=...", "/proxy?url=..."], }, headers=CORS_HEADERS, )
@app.api_route("/api/stream-proxy", methods=["GET", "HEAD", "OPTIONS"])@app.api_route("/proxy", methods=["GET", "HEAD", "OPTIONS"])async def stream_proxy(request: Request, url: str = ""): if request.method == "OPTIONS": return Response(status_code=204, headers=CORS_HEADERS)
raw_url = (url or "").strip() if not raw_url or not ( raw_url.startswith("http://") or raw_url.startswith("https://") ): return Response( content="Invalid or missing target URL", status_code=400, media_type="text/plain", headers=CORS_HEADERS, )
parsed = urllib.parse.urlsplit(raw_url) method = "HEAD" if request.method == "HEAD" else "GET" range_header = request.headers.get("range") lower_url = parsed.path.lower()
# 1. Try ultra-fast direct TCP origin socket for *.testwave.cc tcp_conn = None if is_testwave_host(parsed.hostname or ""): tcp_conn = await open_testwave_tcp(raw_url, method, range_header)
if tcp_conn is not None: status, up_headers, leftover, reader, writer = tcp_conn content_type = up_headers.get("content-type", "").lower() content_length = int(up_headers.get("content-length", "0") or "0") has_range = ("content-range" in up_headers) or (status == 206) is_binary = ( content_type.startswith(("video/", "audio/", "image/")) or lower_url.endswith( (".mp4", ".jpeg", ".jpg", ".png", ".ts", ".m4s", ".aac") ) ) is_potential_playlist = ( method != "HEAD" and not is_binary and not has_range and ( (0 < content_length < 524288) or ( content_length == 0 and (lower_url.endswith(".m3u8") or lower_url.endswith(".docx")) ) ) and ( lower_url.endswith((".m3u8", ".docx", ".pdf")) or "mpegurl" in content_type ) )
if is_potential_playlist: try: rest = await asyncio.wait_for(reader.read(), timeout=20.0) body = leftover + rest finally: try: writer.close() except Exception: pass
if body.lstrip().startswith(b"#EXTM3U"): public_base = get_public_base_origin(request) proxy_prefix = ( f"{public_base}/api/stream-proxy" if public_base else "/api/stream-proxy" ) rewritten = rewrite_hls_playlist( body.decode("utf-8", errors="replace"), raw_url, proxy_prefix ) return Response( content=rewritten, status_code=200, media_type="application/vnd.apple.mpegurl", headers={ **CORS_HEADERS, "Cache-Control": "public, max-age=86400", }, )
out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS) return Response(content=body, status_code=status, headers=out_headers)
out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS)
if method == "HEAD": try: writer.close() except Exception: pass return Response(status_code=status, headers=out_headers)
async def tcp_stream(): try: if leftover: yield leftover while True: if await request.is_disconnected(): break chunk = await reader.read(65536) if not chunk: break yield chunk finally: try: writer.close() except Exception: pass
return StreamingResponse(tcp_stream(), status_code=status, headers=out_headers)
# 2. HTTPX async fallback for any non-testwave CDN or direct HTTPS URLs forward_headers = ( {"Referer": "https://stream.aryavidya.cc/"} if is_testwave_host(parsed.hostname or "") else { "Referer": "https://stream.aryavidya.cc/", "Origin": "https://stream.aryavidya.cc", "User-Agent": FIXED_UA, } ) if range_header: forward_headers["Range"] = range_header
client = httpx.AsyncClient(follow_redirects=True, timeout=30.0) try: req_up = client.build_request(method, raw_url, headers=forward_headers) upstream = await client.send(req_up, stream=True) except Exception as exc: await client.aclose() return Response( content=f"Stream proxy error: {exc}", status_code=502, media_type="text/plain", headers=CORS_HEADERS, )
if upstream.status_code not in (200, 206): st = upstream.status_code await upstream.aclose() await client.aclose() return Response( content=f"Upstream CDN returned {st}", status_code=st, media_type="text/plain", headers=CORS_HEADERS, )
up_headers = {k.lower(): v for k, v in upstream.headers.items()} content_type = up_headers.get("content-type", "").lower() content_length = int(up_headers.get("content-length", "0") or "0") has_range = ("content-range" in up_headers) or (upstream.status_code == 206) is_binary = ( content_type.startswith(("video/", "audio/", "image/")) or lower_url.endswith((".mp4", ".jpeg", ".jpg", ".png", ".ts", ".m4s", ".aac")) ) is_potential_playlist = ( method != "HEAD" and not is_binary and not has_range and ( (0 < content_length < 524288) or ( content_length == 0 and (lower_url.endswith(".m3u8") or lower_url.endswith(".docx")) ) ) and ( lower_url.endswith((".m3u8", ".docx", ".pdf")) or "mpegurl" in content_type ) )
if is_potential_playlist: try: body = await upstream.aread() finally: await upstream.aclose() await client.aclose()
if body.lstrip().startswith(b"#EXTM3U"): public_base = get_public_base_origin(request) proxy_prefix = ( f"{public_base}/api/stream-proxy" if public_base else "/api/stream-proxy" ) rewritten = rewrite_hls_playlist( body.decode("utf-8", errors="replace"), raw_url, proxy_prefix ) return Response( content=rewritten, status_code=200, media_type="application/vnd.apple.mpegurl", headers={ **CORS_HEADERS, "Cache-Control": "public, max-age=86400", }, )
out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS) return Response( content=body, status_code=upstream.status_code, headers=out_headers )
out_headers = {h: up_headers[h] for h in PASS_HEADERS if h in up_headers} if lower_url.endswith((".pdf", ".ts", ".m4s")): out_headers["content-type"] = "video/mp2t" out_headers["Cache-Control"] = "public, max-age=604800, immutable" out_headers.update(CORS_HEADERS)
if method == "HEAD": await upstream.aclose() await client.aclose() return Response(status_code=upstream.status_code, headers=out_headers)
async def httpx_stream(): try: async for chunk in upstream.aiter_bytes(65536): if await request.is_disconnected(): break yield chunk finally: await upstream.aclose() await client.aclose()
return StreamingResponse( httpx_stream(), status_code=upstream.status_code, headers=out_headers )
with gr.Blocks() as demo: gr.Markdown( "# Study Farm Stream Edge\n" "High-speed video streaming proxy is online.\n\n" "- Health check: `/health`\n" "- Stream endpoint: `/api/stream-proxy?url=...`" )
app = gr.mount_gradio_app(app, demo, path="/")
if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info")app.pyAdded+507