Spaces:
Sleeping
Sleeping
Create app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import osimport timeimport asyncioimport loggingfrom pydantic import BaseModelimport httpximport gradio as grfrom fastapi import BackgroundTasks
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
class ProcessRequest(BaseModel): m3u8_url: str chat_id: int bot_token: str show_title: str ep_number: int ep_title: str
async def process_and_upload(data: ProcessRequest): temp_file = f"ep_{data.ep_number}_{int(time.time())}.mp3" try: logger.info(f"Processing stream: {data.show_title} - Ep {data.ep_number}") # FFmpeg stitches the .m3u8 playlist into an MP3 file cmd = [ "ffmpeg", "-y", "-i", data.m3u8_url, "-c:a", "libmp3lame", "-b:a", "64k", temp_file ] proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL ) await proc.wait()
if proc.returncode != 0 or not os.path.exists(temp_file): logger.error("FFmpeg execution failed.") return
# Upload directly to Telegram to save bandwidth tg_url = f"https://api.telegram.org/bot{data.bot_token}/sendAudio" caption = f"🎧 <b>{data.show_title}</b>\n🔹 Episode {data.ep_number} - {data.ep_title}" async with httpx.AsyncClient(timeout=300.0) as client: with open(temp_file, "rb") as f: files = {"audio": (f"{data.show_title}_Ep_{data.ep_number}.mp3", f, "audio/mpeg")} payload = { "chat_id": data.chat_id, "caption": caption, "performer": "Pocket FM", "title": f"Episode {data.ep_number}", "parse_mode": "HTML" } resp = await client.post(tg_url, data=payload, files=files) logger.info(f"Telegram status: {resp.status_code}")
except Exception as e: logger.error(f"Worker task error: {e}") finally: # Immediately delete the MP3 to keep disk storage clean if os.path.exists(temp_file): try: os.remove(temp_file) except Exception: pass
# Minimal Gradio interfacewith gr.Blocks(title="Pocket FM Audio Engine") as demo: gr.Markdown("## ⚡ Pocket FM Cloud FFmpeg Worker is Running!") gr.Markdown("This Space processes .m3u8 streams and delivers episodes to Telegram.")
# Expose the FastAPI backendapp = demo.app
@app.post("/convert")async def convert_episode(req: ProcessRequest, background_tasks: BackgroundTasks): background_tasks.add_task(process_and_upload, req) return {"status": "queued", "ep": req.ep_number}
if __name__ == "__main__": demo.queue().launch(server_name="0.0.0.0", server_port=7860)app.pyAdded+88