Upload 3 files
Browse files- Dockerfile +2 -10
- main.py +223 -0
- requirements.txt +5 -4
Dockerfile
CHANGED
|
@@ -1,11 +1,6 @@
|
|
| 1 |
# Use an official Python runtime as a parent image
|
| 2 |
FROM python:3.10-slim
|
| 3 |
|
| 4 |
-
# Install system dependencies including ffmpeg
|
| 5 |
-
RUN apt-get update && apt-get install -y \
|
| 6 |
-
ffmpeg \
|
| 7 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 8 |
-
|
| 9 |
# Set up a new user 'user' with UID 1000
|
| 10 |
RUN useradd -m -u 1000 user
|
| 11 |
USER user
|
|
@@ -21,11 +16,8 @@ COPY --chown=user . .
|
|
| 21 |
# Install dependencies
|
| 22 |
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 23 |
|
| 24 |
-
# Create a directory for yt-dlp cache
|
| 25 |
-
RUN mkdir -p /tmp/.yt-dlp-cache && chmod 777 /tmp/.yt-dlp-cache
|
| 26 |
-
|
| 27 |
# Expose port 7860
|
| 28 |
EXPOSE 7860
|
| 29 |
|
| 30 |
-
# Start the application using
|
| 31 |
-
CMD ["
|
|
|
|
| 1 |
# Use an official Python runtime as a parent image
|
| 2 |
FROM python:3.10-slim
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
# Set up a new user 'user' with UID 1000
|
| 5 |
RUN useradd -m -u 1000 user
|
| 6 |
USER user
|
|
|
|
| 16 |
# Install dependencies
|
| 17 |
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 18 |
|
|
|
|
|
|
|
|
|
|
| 19 |
# Expose port 7860
|
| 20 |
EXPOSE 7860
|
| 21 |
|
| 22 |
+
# Start the application using uvicorn
|
| 23 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
main.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import socket
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
import logging
|
| 5 |
+
import requests
|
| 6 |
+
from fastapi import FastAPI, HTTPException
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
from ytmusicapi import YTMusic
|
| 9 |
+
from urllib.parse import urlparse, parse_qs
|
| 10 |
+
from typing import Optional, Dict, Any
|
| 11 |
+
|
| 12 |
+
# --- DNS BYPASS PATCH START ---
|
| 13 |
+
BYPASS_DOMAINS = [
|
| 14 |
+
"youtube.com", "music.youtube.com", "googlevideo.com", "youtu.be"
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
import dns.resolver
|
| 19 |
+
_original_getaddrinfo = socket.getaddrinfo
|
| 20 |
+
|
| 21 |
+
def patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
|
| 22 |
+
if host and any(domain in host for domain in BYPASS_DOMAINS):
|
| 23 |
+
try:
|
| 24 |
+
res = dns.resolver.Resolver()
|
| 25 |
+
res.nameservers = ['8.8.8.8', '1.1.1.1']
|
| 26 |
+
answers = res.resolve(host, 'A')
|
| 27 |
+
ip_address = answers[0].to_text()
|
| 28 |
+
return [(socket.AF_INET, type, proto, '', (ip_address, port))]
|
| 29 |
+
except Exception:
|
| 30 |
+
return _original_getaddrinfo(host, port, family, type, proto, flags)
|
| 31 |
+
return _original_getaddrinfo(host, port, family, type, proto, flags)
|
| 32 |
+
|
| 33 |
+
socket.getaddrinfo = patched_getaddrinfo
|
| 34 |
+
print(f"[INIT] DNS Bypass installed for {len(BYPASS_DOMAINS)} domains.", file=sys.stderr)
|
| 35 |
+
except ImportError:
|
| 36 |
+
print("❌ CRITICAL: dnspython not installed. DNS Bypass failed.", file=sys.stderr)
|
| 37 |
+
# --- DNS BYPASS PATCH END ---
|
| 38 |
+
|
| 39 |
+
# Initialize FastAPI and YTMusic
|
| 40 |
+
app = FastAPI()
|
| 41 |
+
ytmusic = YTMusic()
|
| 42 |
+
|
| 43 |
+
# Configure logging
|
| 44 |
+
logging.basicConfig(level=logging.INFO)
|
| 45 |
+
logger = logging.getLogger(__name__)
|
| 46 |
+
|
| 47 |
+
# --- Pydantic Models ---
|
| 48 |
+
|
| 49 |
+
class SearchRequest(BaseModel):
|
| 50 |
+
query: str
|
| 51 |
+
|
| 52 |
+
class MatchRequest(BaseModel):
|
| 53 |
+
url: str
|
| 54 |
+
|
| 55 |
+
class MatchResponse(BaseModel):
|
| 56 |
+
url: str
|
| 57 |
+
filename: str
|
| 58 |
+
track_id: str
|
| 59 |
+
|
| 60 |
+
# --- Helper Functions ---
|
| 61 |
+
|
| 62 |
+
def extract_amazon_track_id(url: str) -> Optional[str]:
|
| 63 |
+
"""
|
| 64 |
+
Extracts track ID from various Amazon Music URL formats.
|
| 65 |
+
"""
|
| 66 |
+
if "music.amazon.com" not in url:
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
parsed_url = urlparse(url)
|
| 70 |
+
query_params = parse_qs(parsed_url.query)
|
| 71 |
+
|
| 72 |
+
if "trackAsin" in query_params:
|
| 73 |
+
return query_params["trackAsin"][0]
|
| 74 |
+
|
| 75 |
+
path_parts = parsed_url.path.split('/')
|
| 76 |
+
if "tracks" in path_parts:
|
| 77 |
+
try:
|
| 78 |
+
track_id_index = path_parts.index("tracks") + 1
|
| 79 |
+
if track_id_index < len(path_parts):
|
| 80 |
+
return path_parts[track_id_index]
|
| 81 |
+
except (ValueError, IndexError):
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
logger.warning(f"Could not extract Amazon track ID from URL: {url}")
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
def get_song_link_info(url: str) -> Optional[Dict[str, Any]]:
|
| 88 |
+
"""
|
| 89 |
+
Fetches track information from the Song.link API.
|
| 90 |
+
"""
|
| 91 |
+
api_base_url = "https://api.song.link/v1-alpha.1/links"
|
| 92 |
+
params = {"userCountry": "US"}
|
| 93 |
+
|
| 94 |
+
if "music.amazon.com" in url:
|
| 95 |
+
track_id = extract_amazon_track_id(url)
|
| 96 |
+
if track_id:
|
| 97 |
+
params["platform"] = "amazonMusic"
|
| 98 |
+
params["id"] = track_id
|
| 99 |
+
params["type"] = "song"
|
| 100 |
+
else:
|
| 101 |
+
params["url"] = url
|
| 102 |
+
else:
|
| 103 |
+
params["url"] = url
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
logger.info(f"Querying Song.link API with params: {params}")
|
| 107 |
+
response = requests.get(api_base_url, params=params, timeout=10)
|
| 108 |
+
response.raise_for_status()
|
| 109 |
+
return response.json()
|
| 110 |
+
except requests.exceptions.RequestException as e:
|
| 111 |
+
logger.error(f"Error fetching from Song.link API: {e}")
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
+
def extract_url(links_by_platform: dict, platform: str) -> Optional[str]:
|
| 115 |
+
"""
|
| 116 |
+
Extracts a specific platform URL from Song.link API response.
|
| 117 |
+
"""
|
| 118 |
+
if platform in links_by_platform and links_by_platform[platform].get("url"):
|
| 119 |
+
return links_by_platform[platform]["url"]
|
| 120 |
+
|
| 121 |
+
logger.warning(f"No URL found for platform '{platform}' in links: {links_by_platform.keys()}")
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
# --- Endpoints ---
|
| 125 |
+
|
| 126 |
+
@app.get("/")
|
| 127 |
+
async def root():
|
| 128 |
+
return {"message": "Music Match API is running. Use /match or /searcht endpoints."}
|
| 129 |
+
|
| 130 |
+
@app.post("/searcht")
|
| 131 |
+
async def searcht(request: SearchRequest):
|
| 132 |
+
"""
|
| 133 |
+
Searches YouTube Music for a song and returns the first result with a videoId.
|
| 134 |
+
"""
|
| 135 |
+
logger.info(f"search query: {request.query}")
|
| 136 |
+
search_results = ytmusic.search(request.query, filter="songs")
|
| 137 |
+
# Return the first song that has a valid videoId, or an empty dict
|
| 138 |
+
first_song = next((song for song in search_results if 'videoId' in song and song['videoId']), {}) if search_results else {}
|
| 139 |
+
return first_song
|
| 140 |
+
|
| 141 |
+
@app.post("/match", response_model=MatchResponse)
|
| 142 |
+
async def match(request: MatchRequest):
|
| 143 |
+
"""
|
| 144 |
+
Matches a given music track URL (Spotify, Apple Music, Amazon, etc.) to a YouTube Music URL.
|
| 145 |
+
"""
|
| 146 |
+
track_url = request.url
|
| 147 |
+
logger.info(f"Match endpoint: Processing URL: {track_url}")
|
| 148 |
+
|
| 149 |
+
track_info = get_song_link_info(track_url)
|
| 150 |
+
if not track_info:
|
| 151 |
+
logger.error(f"Match endpoint: Could not fetch track info for URL: {track_url}")
|
| 152 |
+
raise HTTPException(status_code=404, detail="Could not fetch track info from Song.link API.")
|
| 153 |
+
|
| 154 |
+
entity_unique_id = track_info.get("entityUniqueId")
|
| 155 |
+
title = None
|
| 156 |
+
artist = None
|
| 157 |
+
|
| 158 |
+
# Attempt to find main entity details
|
| 159 |
+
if entity_unique_id and entity_unique_id in track_info.get("entitiesByUniqueId", {}):
|
| 160 |
+
main_entity = track_info["entitiesByUniqueId"][entity_unique_id]
|
| 161 |
+
title = main_entity.get("title")
|
| 162 |
+
artist = main_entity.get("artistName")
|
| 163 |
+
logger.info(f"Match endpoint: Found main entity - Title: '{title}', Artist: '{artist}'")
|
| 164 |
+
else:
|
| 165 |
+
logger.warning(f"Match endpoint: Could not find main entity details for {track_url} using entityUniqueId: {entity_unique_id}")
|
| 166 |
+
|
| 167 |
+
# Fallback logic to find title/artist from other entities
|
| 168 |
+
for entity_id, entity_data in track_info.get("entitiesByUniqueId", {}).items():
|
| 169 |
+
if entity_data.get("title") and entity_data.get("artistName"):
|
| 170 |
+
title = entity_data.get("title")
|
| 171 |
+
artist = entity_data.get("artistName")
|
| 172 |
+
logger.info(f"Match endpoint: Using fallback entity - Title: '{title}', Artist: '{artist}' from entity ID {entity_id}")
|
| 173 |
+
break
|
| 174 |
+
|
| 175 |
+
if not title or not artist:
|
| 176 |
+
logger.error(f"Match endpoint: Could not determine title and artist for URL: {track_url}")
|
| 177 |
+
raise HTTPException(status_code=404, detail="Could not determine title and artist from Song.link info.")
|
| 178 |
+
|
| 179 |
+
# Try to find a direct YouTube link from the API response
|
| 180 |
+
youtube_url = extract_url(track_info.get("linksByPlatform", {}), "youtube")
|
| 181 |
+
|
| 182 |
+
if youtube_url:
|
| 183 |
+
video_id = None
|
| 184 |
+
|
| 185 |
+
# Extract Video ID from URL
|
| 186 |
+
if "v=" in youtube_url:
|
| 187 |
+
video_id = youtube_url.split("v=")[1].split("&")[0]
|
| 188 |
+
elif "youtu.be/" in youtube_url:
|
| 189 |
+
video_id = youtube_url.split("youtu.be/")[1].split("?")[0]
|
| 190 |
+
|
| 191 |
+
filename = f"{title} - {artist}" if title and artist else "Unknown Track - Unknown Artist"
|
| 192 |
+
logger.info(f"Match endpoint: Found direct YouTube URL: {youtube_url}, Video ID: {video_id}")
|
| 193 |
+
|
| 194 |
+
return MatchResponse(url=youtube_url, filename=filename, track_id=video_id)
|
| 195 |
+
else:
|
| 196 |
+
# Fallback: Search YouTube Music
|
| 197 |
+
logger.info(f"Match endpoint: No direct YouTube URL. Searching YTMusic with: '{title} - {artist}'")
|
| 198 |
+
|
| 199 |
+
search_query = f'{title} {artist}'
|
| 200 |
+
search_results = ytmusic.search(search_query, filter="songs")
|
| 201 |
+
|
| 202 |
+
if search_results:
|
| 203 |
+
first_song = next((song for song in search_results if song.get('videoId')), None)
|
| 204 |
+
|
| 205 |
+
if first_song and first_song.get('videoId'):
|
| 206 |
+
video_id = first_song["videoId"]
|
| 207 |
+
ym_url = f'https://music.youtube.com/watch?v={video_id}'
|
| 208 |
+
|
| 209 |
+
# Get artist name safely
|
| 210 |
+
artist_name = artist
|
| 211 |
+
if first_song.get('artists') and len(first_song['artists']) > 0:
|
| 212 |
+
artist_name = first_song['artists'][0]['name']
|
| 213 |
+
|
| 214 |
+
filename = f"{first_song.get('title', title)} - {artist_name}"
|
| 215 |
+
logger.info(f"Match endpoint: Found YTMusic search result - URL: {ym_url}, Video ID: {video_id}")
|
| 216 |
+
|
| 217 |
+
return MatchResponse(filename=filename, url=ym_url, track_id=video_id)
|
| 218 |
+
else:
|
| 219 |
+
logger.error(f"Match endpoint: YTMusic search for '{search_query}' yielded no results with a videoId.")
|
| 220 |
+
raise HTTPException(status_code=404, detail="No matching video ID found on YouTube Music after search.")
|
| 221 |
+
else:
|
| 222 |
+
logger.error(f"Match endpoint: YTMusic search for '{search_query}' yielded no results.")
|
| 223 |
+
raise HTTPException(status_code=404, detail="No results found on YouTube Music for the track.")
|
requirements.txt
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
| 3 |
dnspython
|
| 4 |
-
gunicorn
|
| 5 |
-
cachetools
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
pydantic
|
| 4 |
+
ytmusicapi
|
| 5 |
+
requests
|
| 6 |
dnspython
|
|
|
|
|
|