import os import io import json import sqlite3 import asyncio from typing import Optional os.environ["GRADIO_SSR_MODE"] = "false" import spaces @spaces.GPU def _zero_gpu_warmup(): pass import gradio as gr import uvicorn from fastapi import FastAPI, Request, HTTPException from fastapi.responses import StreamingResponse, Response, FileResponse, HTMLResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from telethon import TelegramClient from telethon.tl.types import DocumentAttributeAudio, DocumentAttributeFilename from mutagen.flac import FLAC # Use /tmp/aether_data because Hugging Face Spaces (/app) is read-only for UID 1000 DATA_DIR = "/tmp/aether_data" COVERS_DIR = os.path.join(DATA_DIR, "covers") CONFIG_PATH = os.path.join(DATA_DIR, "config.json") DB_PATH = os.path.join(DATA_DIR, "catalogue.db") SESSION_PATH = os.path.join(DATA_DIR, "aether_lossless_session") os.makedirs(COVERS_DIR, exist_ok=True) app = FastAPI(title="Aether Lossless Telegram Server") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) client: Optional[TelegramClient] = None def init_db(): conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute(""" CREATE TABLE IF NOT EXISTS tracks ( msg_id INTEGER PRIMARY KEY, title TEXT, artist TEXT, album TEXT, genre TEXT, year TEXT, track_num INTEGER, duration REAL, bit_depth INTEGER, sample_rate INTEGER, channels INTEGER, file_size INTEGER, mime_type TEXT, has_cover INTEGER DEFAULT 0 ) """) conn.commit() conn.close() init_db() def load_config(): if os.path.exists(CONFIG_PATH): with open(CONFIG_PATH, "r") as f: return json.load(f) return { "api_id": int(os.getenv("TG_API_ID", "0")), "api_hash": os.getenv("TG_API_HASH", ""), "channel_id": int(os.getenv("TG_CHANNEL_ID", "0")) } def save_config(cfg): with open(CONFIG_PATH, "w") as f: json.dump(cfg, f, indent=2) async def ensure_client(): global client cfg = load_config() if not cfg["api_id"] or not cfg["api_hash"]: return None if client is None: client = TelegramClient(SESSION_PATH, int(cfg["api_id"]), cfg["api_hash"]) await client.connect() return client class SetupRequest(BaseModel): api_id: int api_hash: str channel_id: int phone: str class VerifyRequest(BaseModel): phone: str code: str password: Optional[str] = None @app.get("/api/status") async def get_status(): cfg = load_config() if not cfg["api_id"] or not cfg["api_hash"] or not cfg["channel_id"]: return {"configured": False, "authorized": False} cl = await ensure_client() if not cl: return {"configured": False, "authorized": False} authorized = await cl.is_user_authorized() return {"configured": True, "authorized": authorized, "channel_id": cfg["channel_id"]} @app.post("/api/auth/send_code") async def send_auth_code(req: SetupRequest): global client save_config({"api_id": req.api_id, "api_hash": req.api_hash, "channel_id": req.channel_id}) if client: await client.disconnect() client = TelegramClient(SESSION_PATH, req.api_id, req.api_hash) await client.connect() if not await client.is_user_authorized(): await client.send_code_request(req.phone) return {"status": "code_sent"} return {"status": "already_authorized"} @app.post("/api/auth/verify") async def verify_auth_code(req: VerifyRequest): cl = await ensure_client() if not cl: raise HTTPException(status_code=400, detail="Client not initialized") try: await cl.sign_in(req.phone, req.code) except Exception as e: if "SessionPasswordNeededError" in str(type(e)) and req.password: await cl.sign_in(password=req.password) else: raise HTTPException(status_code=400, detail=str(e)) return {"status": "authorized"} async def extract_flac_header_metadata(cl: TelegramClient, msg): header_bytes = bytearray() async for chunk in cl.iter_download(msg.document, offset=0, request_size=65536): header_bytes.extend(chunk) if len(header_bytes) >= 524288: break meta = { "title": None, "artist": None, "album": "Single / Unknown Album", "genre": "Lossless", "year": "", "track_num": 0, "duration": 0.0, "bit_depth": 16, "sample_rate": 44100, "channels": 2, "has_cover": 0 } for attr in msg.document.attributes: if isinstance(attr, DocumentAttributeAudio): meta["title"] = attr.title meta["artist"] = attr.performer meta["duration"] = float(attr.duration or 0) elif isinstance(attr, DocumentAttributeFilename): if not meta["title"]: meta["title"] = os.path.splitext(attr.file_name)[0] cover_file = os.path.join(COVERS_DIR, f"{msg.id}.jpg") try: bio = io.BytesIO(bytes(header_bytes)) flac = FLAC(bio) if flac.info: meta["bit_depth"] = getattr(flac.info, "bits_per_sample", 16) meta["sample_rate"] = getattr(flac.info, "sample_rate", 44100) meta["channels"] = getattr(flac.info, "channels", 2) meta["duration"] = float(getattr(flac.info, "length", meta["duration"])) if flac.tags: meta["title"] = flac.tags.get("title", [meta["title"]])[0] meta["artist"] = flac.tags.get("artist", [meta["artist"] or "Unknown Artist"])[0] meta["album"] = flac.tags.get("album", [meta["album"]])[0] meta["genre"] = flac.tags.get("genre", [meta["genre"]])[0] meta["year"] = flac.tags.get("date", flac.tags.get("year", [""]))[0] tr = flac.tags.get("tracknumber", ["0"])[0] meta["track_num"] = int(str(tr).split("/")[0]) if str(tr).split("/")[0].isdigit() else 0 if flac.pictures: pic = flac.pictures[0] with open(cover_file, "wb") as cf: cf.write(pic.data) meta["has_cover"] = 1 except Exception: try: thumb = await cl.download_media(msg, thumb=-1, file=bytes) if thumb: with open(cover_file, "wb") as cf: cf.write(thumb) meta["has_cover"] = 1 except Exception: pass if not meta["title"]: meta["title"] = f"Track {msg.id}" if not meta["artist"]: meta["artist"] = "Unknown Artist" return meta @app.post("/api/sync") async def sync_catalogue(): cl = await ensure_client() cfg = load_config() if not cl or not await cl.is_user_authorized(): raise HTTPException(status_code=401, detail="Telegram not authorized") channel_id = int(cfg["channel_id"]) conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute("SELECT msg_id FROM tracks") existing_ids = {row[0] for row in c.fetchall()} added = 0 async for msg in cl.iter_messages(channel_id, limit=500): if msg.id in existing_ids: continue if msg.document and msg.file: mime = (msg.file.mime_type or "").lower() fname = (msg.file.name or "").lower() if "audio" in mime or fname.endswith((".flac", ".m4a", ".alac", ".wav")): meta = await extract_flac_header_metadata(cl, msg) c.execute(""" INSERT OR REPLACE INTO tracks (msg_id, title, artist, album, genre, year, track_num, duration, bit_depth, sample_rate, channels, file_size, mime_type, has_cover) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( msg.id, meta["title"], meta["artist"], meta["album"], meta["genre"], meta["year"], meta["track_num"], meta["duration"], meta["bit_depth"], meta["sample_rate"], meta["channels"], msg.file.size, msg.file.mime_type or "audio/flac", meta["has_cover"] )) conn.commit() added += 1 conn.close() return {"status": "synced", "new_tracks_indexed": added} @app.get("/api/catalogue") async def get_catalogue(): conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row c = conn.cursor() c.execute("SELECT * FROM tracks ORDER BY album ASC, track_num ASC, msg_id DESC") rows = [dict(r) for r in c.fetchall()] conn.close() return rows @app.get("/api/cover/{msg_id}") async def get_cover(msg_id: int): cover_path = os.path.join(COVERS_DIR, f"{msg_id}.jpg") if os.path.exists(cover_path): return FileResponse(cover_path, media_type="image/jpeg") cl = await ensure_client() cfg = load_config() if cl and await cl.is_user_authorized(): msg = await cl.get_messages(int(cfg["channel_id"]), ids=msg_id) if msg: thumb = await cl.download_media(msg, thumb=-1, file=bytes) if thumb: with open(cover_path, "wb") as f: f.write(thumb) return Response(content=thumb, media_type="image/jpeg") raise HTTPException(status_code=404, detail="Cover not found") @app.get("/api/stream/{msg_id}") async def stream_lossless(msg_id: int, request: Request): cl = await ensure_client() cfg = load_config() if not cl or not await cl.is_user_authorized(): raise HTTPException(status_code=401, detail="Unauthorized") msg = await cl.get_messages(int(cfg["channel_id"]), ids=msg_id) if not msg or not msg.document: raise HTTPException(status_code=404, detail="Track not found in Telegram channel") file_size = msg.file.size range_header = request.headers.get("Range") offset = 0 end = file_size - 1 if range_header: parts = range_header.replace("bytes=", "").split("-") offset = int(parts[0]) if parts[0] else 0 if len(parts) > 1 and parts[1]: end = int(parts[1]) aligned_offset = offset - (offset % 4096) skip_bytes = offset - aligned_offset content_length = end - offset + 1 async def chunk_generator(): first = True remaining = content_length async for chunk in cl.iter_download(msg.document, offset=aligned_offset, request_size=65536): if first and skip_bytes: chunk = chunk[skip_bytes:] first = False if len(chunk) >= remaining: yield chunk[:remaining] break remaining -= len(chunk) yield chunk headers = { "Content-Range": f"bytes {offset}-{end}/{file_size}", "Accept-Ranges": "bytes", "Content-Length": str(content_length), "Cache-Control": "public, max-age=86400" } return StreamingResponse( chunk_generator(), status_code=206 if range_header else 200, media_type=msg.file.mime_type or "audio/flac", headers=headers ) INDEX_HTML = '\n\n\n \n \n Aether • Lossless Music Streamer\n \n \n\n\n
\n\n
\n \n \n\n \n
\n
\n

Lossless Catalogue

\n \n
\n
\n
\n\n \n
\n
\n \n \n
\n\n \n
\n

Select any lossless track from your catalogue to stream and load time-synced lyrics.

\n
\n\n \n \n
\n
\n\n \n
\n
\n \n
\n
Ready to Stream
\n
Telegram Lossless Server
\n
LOSSLESS FLAC
\n
\n
\n\n
\n
\n \n \n \n \n
\n
\n 0:00\n \n 0:00\n
\n
\n\n
\n 🔊\n \n
\n
\n\n \n\n \n \n\n \n\n\n' MANIFEST_JSON = '{\n "name": "Aether Lossless Music",\n "short_name": "Aether",\n "description": "Bit-Perfect 24-Bit Lossless Music Player powered by Telegram Cloud",\n "start_url": "/",\n "display": "standalone",\n "background_color": "#07080c",\n "theme_color": "#07080c",\n "icons": [\n {\n "src": "https://cdn-icons-png.flaticon.com/512/3844/3844724.png",\n "sizes": "512x512",\n "type": "image/png"\n }\n ]\n}\n' @app.get("/manifest.json") async def serve_manifest(): return Response(content=MANIFEST_JSON, media_type="application/json") @app.get("/player") async def serve_player(): return HTMLResponse(content=INDEX_HTML) # Real Gradio Blocks App so Hugging Face Gradio 6.30 & ZeroGPU runtime checks pass 100% natively! with gr.Blocks(title="Aether Lossless") as demo: gr.HTML("""
""") # Mount the real Gradio app onto our FastAPI server app = gr.mount_gradio_app(app, demo, path="/", ssr_mode=False) if __name__ == "__main__": port = int(os.environ.get("GRADIO_SERVER_PORT", 7860)) uvicorn.run(app, host="0.0.0.0", port=port)