-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi_server.py
More file actions
204 lines (159 loc) · 5.22 KB
/
api_server.py
File metadata and controls
204 lines (159 loc) · 5.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""
Lucida Flow API Server
FastAPI REST API for Lucida.to music downloads
"""
from fastapi import FastAPI, HTTPException, Response
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, HttpUrl
from typing import Optional, List
import os
from dotenv import load_dotenv
from lucida_client import LucidaClient
import uvicorn
# Load environment variables
load_dotenv()
app = FastAPI(
title="Lucida Flow API",
description="REST API for downloading music via Lucida.to",
version="1.0.0",
)
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global client instance
lucida_client = LucidaClient()
# Request/Response Models
class SearchRequest(BaseModel):
query: str
service: str
limit: Optional[int] = 10
class TrackInfoRequest(BaseModel):
url: str
class DownloadRequest(BaseModel):
url: str
output_path: Optional[str] = None
@app.get("/")
async def root():
"""API root endpoint"""
return {
"name": "Lucida Flow API",
"version": "1.0.0",
"endpoints": {
"GET /health": "Health check",
"GET /services": "List available services",
"POST /search": "Search for music",
"POST /info": "Get track information",
"POST /download": "Download track",
},
}
@app.get("/health")
async def health():
"""Health check endpoint"""
return {
"status": "healthy",
"service": "Lucida Flow API",
"base_url": lucida_client.base_url,
}
@app.get("/services")
async def get_services():
"""Get list of available streaming services"""
services = lucida_client.get_available_services()
return {"services": services, "count": len(services)}
@app.post("/search")
async def search(request: SearchRequest):
"""
Search for music on a specific streaming service
- **query**: Search query string
- **service**: Music service (tidal, qobuz, spotify, deezer, soundcloud, amazon_music, yandex_music)
- **limit**: Maximum number of results (default: 10)
"""
try:
results = lucida_client.search(
request.query, service=request.service, limit=request.limit or 10
)
if "error" in results:
raise HTTPException(status_code=500, detail=results["error"])
return results
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/info")
async def get_track_info(request: TrackInfoRequest):
"""
Get detailed information about a track
- **url**: URL to the track (from Tidal, Qobuz, Spotify, etc.)
"""
try:
info = lucida_client.get_track_info(request.url)
if "error" in info:
raise HTTPException(status_code=500, detail=info["error"])
return info
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/download")
async def download_track(request: DownloadRequest):
"""
Download a track and return file information
- **url**: URL to the track
- **output_path**: Optional output path for the file
"""
try:
result = lucida_client.download_track(
request.url, output_path=request.output_path
)
if not result.get("success"):
raise HTTPException(
status_code=500, detail=result.get("error", "Download failed")
)
return {
"success": True,
"filepath": result["filepath"],
"size": result["size"],
"size_mb": round(result["size"] / 1024 / 1024, 2),
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/download-file")
async def download_track_file(request: DownloadRequest):
"""
Download a track and return the audio file directly
- **url**: URL to the track
"""
try:
# Download to temporary location
result = lucida_client.download_track(request.url)
if not result.get("success"):
raise HTTPException(
status_code=500, detail=result.get("error", "Download failed")
)
filepath = result["filepath"]
# Read file content
with open(filepath, "rb") as f:
content = f.read()
# Determine content type
if filepath.endswith(".flac"):
media_type = "audio/flac"
elif filepath.endswith(".mp3"):
media_type = "audio/mpeg"
elif filepath.endswith(".m4a"):
media_type = "audio/mp4"
else:
media_type = "application/octet-stream"
filename = os.path.basename(filepath)
return Response(
content=content,
media_type=media_type,
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
host = os.getenv("API_HOST", "0.0.0.0")
port = int(os.getenv("API_PORT", 8000))
print(f"Starting Lucida Flow API on {host}:{port}")
print(f"API Documentation: http://{host}:{port}/docs")
uvicorn.run(app, host=host, port=port)