import os import random import string import httpx from typing import Optional def download_audio(url: str, temp_dir: str, timeout: int = 120) -> Optional[str]: os.makedirs(temp_dir, exist_ok=True) headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "audio/mpeg,*/*", } file_ext = ".mp3" with httpx.Client(timeout=timeout, follow_redirects=True) as client: with client.stream("GET", url, headers=headers) as resp: if resp.status_code != 200: return None ct = resp.headers.get("content-type", "") if "ogg" in ct: file_ext = ".ogg" elif "wav" in ct: file_ext = ".wav" elif "m4a" in ct or "mp4" in ct: file_ext = ".m4a" cd = resp.headers.get("content-disposition", "") m = None if cd: import re m = re.search(r'filename=(.+)', cd) if m: fname = m.group(1).strip('"').strip("'") else: suffix = "".join(random.choices(string.ascii_lowercase, k=6)) fname = f"call_{suffix}{file_ext}" local_path = os.path.join(temp_dir, fname) with open(local_path, "wb") as f: for chunk in resp.iter_bytes(chunk_size=8192): f.write(chunk) return local_path