Update app.py
Browse files442 unmodified lines443444445446447448196 unmodified lines645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682456 unmodified lines11391140114111421143114411451146114711481149115011511152115311541155442 unmodified linesTIDAL_CLIENT_SECRET = '1Nn9AfDAjxrgJFJbKNWLeAyKGVGmINuXPPLHVXAvxAg='QOBUZ_APP_ID = "798273057"QOBUZ_TOKEN = "24C11TFdqY955_VMFQeIUgQD4Fl8LRYl3l6NupLzpbQlQ_4qOKNsIQIaIC1pWTG2UchFvaER8WN15GZCe4__-w"QQ_SETTINGS = {"SECRET": "ZdJqM15EeO2zWc08","APP_KEY": "0AND0HD6FE4HY80F",196 unmodified linesasync def search_qobuz_async(search_query: str, target_title: str, target_artist: str):headers = {"X-App-Id": QOBUZ_APP_ID,"X-User-Auth-Token": QOBUZ_TOKEN,"User-Agent": "Mozilla/5.0"}async with httpx.AsyncClient(timeout=10.0, trust_env=False) as client:try:resp = await client.get("https://www.qobuz.com/api.json/0.2/track/search",headers=headers,params={"query": search_query, "limit": 5})if resp.status_code == 200:data = resp.json()tracks = data.get("tracks", {}).get("items", [])if tracks:best_match_url = Nonehighest_score = 0.0for track in tracks:t_title = track.get("title", "")t_artists = track.get("performer", {}).get("name", "")title_score = similar(clean_title(target_title), clean_title(t_title))artist_score = similar(target_artist, t_artists)total_score = (title_score * 0.6) + (artist_score * 0.4)if title_score > 0.8: total_score += 0.2if total_score > highest_score:highest_score = total_scorebest_match_url = f"https://www.qobuz.com/track/{track['id']}"if highest_score >= 0.4:return best_match_urlexcept Exception as e:print(f"Qobuz search error: {e}")return None456 unmodified linesqobuz_id = path_parts[-1]is_track = "track/" in parsed_url.pathendpoint = "track/get" if is_track else "album/get"api_url = f"https://www.qobuz.com/api.json/0.2/{endpoint}"headers = {"X-App-Id": QOBUZ_APP_ID,"X-User-Auth-Token": QOBUZ_TOKEN,"User-Agent": "Mozilla/5.0"}params = {"track_id" if is_track else "album_id": qobuz_id}async with httpx.AsyncClient(timeout=10.0, trust_env=False) as client:response = await client.get(api_url, params=params, headers=headers)if response.status_code != 200:raise HTTPException(status_code=400, detail=f"Qobuz API error: {response.status_code}")data = response.json()track_title = data.get("title", "")artist_data = data.get("artist") or data.get("performer") or data.get("album", {}).get("artist")442 unmodified lines443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500196 unmodified lines697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729456 unmodified lines1186118711881189119011911192119311941195119611971198442 unmodified linesTIDAL_CLIENT_SECRET = '1Nn9AfDAjxrgJFJbKNWLeAyKGVGmINuXPPLHVXAvxAg='QOBUZ_APP_ID = "798273057"QOBUZ_TOKEN = "24C11TFdqY955_VMFQeIUgQD4Fl8LRYl3l6NupLzpbQlQ_4qOKNsIQIaIC1pWTG2UchFvaER8WN15GZCe4__-w"# Optional escape hatch: route Qobuz traffic through a user-supplied proxy# (e.g. a residential/US proxy) when the Space egress IP is blocked.QOBUZ_PROXY = os.getenv('QOBUZ_PROXY')async def _qobuz_api_get(path: str, params: dict):"""GET a Qobuz API endpoint with adaptive transport selection.Qobuz returns 403 to some datacenter egress IPs (including some HF Spacepaths). We try, in order:1. custom QOBUZ_PROXY if configured2. direct connection, ignoring platform proxy env vars (trust_env=False)3. via platform proxy env vars (trust_env=True)and return the first 200 response. Returns None if every path fails."""url = f"https://www.qobuz.com/api.json/0.2/{path}"headers = {"X-App-Id": QOBUZ_APP_ID,"X-User-Auth-Token": QOBUZ_TOKEN,"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ""(KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"),"Accept": "application/json, text/plain, */*","Accept-Language": "en-US,en;q=0.9","Referer": "https://www.qobuz.com/","Origin": "https://www.qobuz.com",}# Each candidate is (label, httpx client kwargs)candidates = []if QOBUZ_PROXY:candidates.append(("custom-proxy", {"trust_env": False, "proxy": QOBUZ_PROXY}))candidates.append(("direct", {"trust_env": False}))candidates.append(("platform-proxy", {"trust_env": True}))for label, client_kwargs in candidates:try:async with httpx.AsyncClient(timeout=10.0, **client_kwargs) as client:resp = await client.get(url, headers=headers, params=params)if resp.status_code == 200:logger.info(f"qobuz {path} via {label}: 200")return resplogger.info(f"qobuz {path} via {label}: {resp.status_code} "f"| server={resp.headers.get('server')} | body={resp.text[:150]!r}")except Exception as e:logger.info(f"qobuz {path} via {label}: {type(e).__name__}: {str(e)[:120]}")return NoneQQ_SETTINGS = {"SECRET": "ZdJqM15EeO2zWc08","APP_KEY": "0AND0HD6FE4HY80F",196 unmodified linesasync def search_qobuz_async(search_query: str, target_title: str, target_artist: str):resp = await _qobuz_api_get("track/search",{"query": search_query, "limit": 5},)if resp is None:print("Qobuz search error: all transports failed (403/blocked)")return Nonetry:data = resp.json()tracks = data.get("tracks", {}).get("items", [])if tracks:best_match_url = Nonehighest_score = 0.0for track in tracks:t_title = track.get("title", "")t_artists = track.get("performer", {}).get("name", "")title_score = similar(clean_title(target_title), clean_title(t_title))artist_score = similar(target_artist, t_artists)total_score = (title_score * 0.6) + (artist_score * 0.4)if title_score > 0.8: total_score += 0.2if total_score > highest_score:highest_score = total_scorebest_match_url = f"https://www.qobuz.com/track/{track['id']}"if highest_score >= 0.4:return best_match_urlexcept Exception as e:print(f"Qobuz search error: {e}")return None456 unmodified linesqobuz_id = path_parts[-1]is_track = "track/" in parsed_url.pathendpoint = "track/get" if is_track else "album/get"params = {"track_id" if is_track else "album_id": qobuz_id}response = await _qobuz_api_get(endpoint, params)if response is None:raise HTTPException(status_code=400,detail="Qobuz API error: blocked (403) from this server. Set QOBUZ_PROXY or retry later.",)data = response.json()track_title = data.get("title", "")artist_data = data.get("artist") or data.get("performer") or data.get("album", {}).get("artist")
app.py+85-42