jumannendange commited on
Commit
ee88dcd
·
verified ·
1 Parent(s): 778fd7d

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -163
app.py DELETED
@@ -1,163 +0,0 @@
1
- """
2
- JAYNES DL Proxy — Hugging Face Space (SDK: gradio, hakuna Docker)
3
- GET /dl?url=<encoded>&filename=<jina.mp4>
4
- - Inasukuma (stream) faili bila kulihifadhi kwenye server
5
- - Range/resume, retry ya 429/5xx kwa backoff, Referer + User-Agent sahihi
6
- - CORS wazi, Content-Disposition: attachment
7
-
8
- Njia: Gradio ndiye anayeanzisha server (port 7860). Route ya /dl
9
- inawekwa ndani ya server hiyo hiyo — hakuna uvicorn.run() wa pili.
10
- """
11
- import os
12
-
13
- # Zima SSR ya Gradio (Node proxy) ili routes zetu zifike moja kwa moja.
14
- os.environ.setdefault("GRADIO_SSR_MODE", "False")
15
-
16
- import asyncio
17
- import random
18
- import re
19
- from urllib.parse import quote, urlparse
20
-
21
- import gradio as gr
22
- import httpx
23
- from fastapi import Request
24
- from fastapi.responses import PlainTextResponse, StreamingResponse
25
- from starlette.background import BackgroundTask
26
-
27
- # ZeroGPU inahitaji angalau function moja yenye @spaces.GPU wakati wa startup.
28
- # Placeholder tu; haiitwi kamwe. (Kama Space iko kwenye CPU basic, haina madhara.)
29
- try:
30
- import spaces
31
-
32
- @spaces.GPU
33
- def _gpu_placeholder() -> str:
34
- return "ok"
35
- except ImportError:
36
- pass
37
-
38
- ALLOWED = [
39
- re.compile(r"(^|\.)hakunaymatata\.com$", re.I),
40
- re.compile(r"(^|\.)aoneroom\.com$", re.I),
41
- ]
42
- UA = ("Mozilla/5.0 (Linux; Android 13; Mobile) AppleWebKit/537.36 "
43
- "(KHTML, like Gecko) Chrome/124.0 Mobile Safari/537.36")
44
- PASS_HEADERS = ["content-type", "content-length", "content-range",
45
- "accept-ranges", "etag", "last-modified"]
46
- CORS = {
47
- "access-control-allow-origin": "*",
48
- "access-control-allow-methods": "GET, HEAD, OPTIONS",
49
- "access-control-allow-headers": "*",
50
- "access-control-expose-headers": "content-length, content-range, "
51
- "accept-ranges, content-type, content-disposition",
52
- }
53
-
54
- client = httpx.AsyncClient(
55
- timeout=httpx.Timeout(connect=20, read=120, write=20, pool=20),
56
- follow_redirects=True,
57
- limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
58
- )
59
-
60
-
61
- def host_ok(host: str) -> bool:
62
- return any(p.search(host or "") for p in ALLOWED)
63
-
64
-
65
- async def open_upstream(method: str, url: str, rng: str | None):
66
- u = urlparse(url)
67
- headers = {
68
- "User-Agent": UA,
69
- "Accept": "*/*",
70
- "Accept-Encoding": "identity",
71
- "Referer": f"{u.scheme}://{u.netloc}/",
72
- }
73
- if rng:
74
- headers["Range"] = rng
75
- last = None
76
- for attempt in range(5):
77
- req = client.build_request(method, url, headers=headers)
78
- res = await client.send(req, stream=True)
79
- if res.status_code != 429 and res.status_code < 500:
80
- return res
81
- last = res
82
- ra = res.headers.get("retry-after")
83
- wait = min(float(ra), 8) if ra and ra.replace(".", "", 1).isdigit() \
84
- else min(0.7 * 2 ** attempt, 6) + random.random() * 0.3
85
- if attempt < 4:
86
- await res.aclose()
87
- await asyncio.sleep(wait)
88
- return last
89
-
90
-
91
- async def dl(request: Request, url: str = "", filename: str = "video.mp4"):
92
- if not url:
93
- return PlainTextResponse("Missing url", status_code=400, headers=CORS)
94
- try:
95
- host = urlparse(url).hostname or ""
96
- if urlparse(url).scheme not in ("http", "https"):
97
- raise ValueError
98
- except Exception:
99
- return PlainTextResponse("Bad url", status_code=400, headers=CORS)
100
- if not host_ok(host):
101
- return PlainTextResponse("Host not allowed", status_code=403, headers=CORS)
102
-
103
- try:
104
- up = await open_upstream(request.method, url, request.headers.get("range"))
105
- except Exception as e: # noqa: BLE001
106
- return PlainTextResponse(f"Upstream error: {e}", status_code=502, headers=CORS)
107
-
108
- headers = {k: up.headers[k] for k in PASS_HEADERS if k in up.headers}
109
- if up.status_code < 400:
110
- ct = headers.get("content-type", "")
111
- if not ct or "text/html" in ct.lower():
112
- headers["content-type"] = "video/mp4"
113
- headers.setdefault("accept-ranges", "bytes")
114
- safe = re.sub(r'[\r\n"\\/]', "_", filename or "video.mp4")
115
- ascii_name = re.sub(r"[^\x20-\x7e]", "_", safe)
116
- headers["content-disposition"] = (
117
- f'attachment; filename="{ascii_name}"; filename*=UTF-8\'\'{quote(safe)}')
118
- headers["cache-control"] = "no-store"
119
- headers.update(CORS)
120
-
121
- if request.method == "HEAD":
122
- await up.aclose()
123
- return PlainTextResponse("", status_code=up.status_code, headers=headers)
124
-
125
- return StreamingResponse(
126
- up.aiter_raw(chunk_size=256 * 1024),
127
- status_code=up.status_code,
128
- headers=headers,
129
- background=BackgroundTask(up.aclose),
130
- )
131
-
132
-
133
- async def dl_options(request: Request):
134
- return PlainTextResponse("", status_code=204, headers=CORS)
135
-
136
-
137
- # ── UI ndogo ya Gradio ──
138
- def build_link(url: str, filename: str) -> str:
139
- if not url:
140
- return "Weka URL ya video."
141
- return f"/dl?url={quote(url, safe='')}&filename={quote(filename or 'video.mp4')}"
142
-
143
-
144
- with gr.Blocks(title="JAYNES DL Proxy") as demo:
145
- gr.Markdown("### JAYNES DL Proxy — OK\nTumia: `/dl?url=<encoded>&filename=<jina.mp4>`")
146
- u = gr.Textbox(label="Video URL")
147
- f = gr.Textbox(label="Filename", value="video.mp4")
148
- out = gr.Textbox(label="Proxy link (jaribu)")
149
- gr.Button("Tengeneza link").click(build_link, [u, f], out)
150
-
151
-
152
- demo.queue(max_size=20)
153
- demo.launch(prevent_thread_lock=True)
154
-
155
- # Ongeza routes zetu mbele ya routes za Gradio ili zipate kipaumbele
156
- _fastapi = demo.app
157
- _before = len(_fastapi.router.routes)
158
- _fastapi.add_api_route("/dl", dl, methods=["GET", "HEAD"])
159
- _fastapi.add_api_route("/dl", dl_options, methods=["OPTIONS"])
160
- _new = _fastapi.router.routes[_before:]
161
- _fastapi.router.routes[:] = _new + _fastapi.router.routes[:_before]
162
-
163
- demo.block_thread()