Spaces:
Build error
Build error
feat: backend API routes servisleri ve tests için commend data processing dreams ve remix features eklendi
Browse files- app/routes/commend/router.py +6 -4
- app/routes/data_processing.py +11 -9
- app/routes/dreams.py +6 -2
- app/routes/remix.py +8 -7
- app/services/dream_analyzer.py +21 -5
- app/services/tool_gate.py +62 -0
- tests/test_tool_gate.py +182 -0
app/routes/commend/router.py
CHANGED
|
@@ -119,7 +119,9 @@ class CommendHealthResponse(BaseModel):
|
|
| 119 |
|
| 120 |
_COMMEND_API_KEY = os.getenv("COMMEND_API_KEY")
|
| 121 |
_COMMEND_POSTING_ENABLED = os.getenv("COMMEND_ENABLE_POSTING", "false").lower() == "true"
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
|
| 124 |
# Simple in-memory rate limiter: IP -> list of timestamps
|
| 125 |
_rate_limit_store: dict[str, list[float]] = defaultdict(list)
|
|
@@ -232,7 +234,7 @@ async def commend_health_check():
|
|
| 232 |
|
| 233 |
|
| 234 |
@router.post("/video-details", response_model=VideoDetailsResponse, dependencies=[Depends(_rate_limit_only)])
|
| 235 |
-
|
| 236 |
"""
|
| 237 |
Fetch video details without generating a comment.
|
| 238 |
Useful for preview before generation.
|
|
@@ -256,7 +258,7 @@ async def get_video_info(request: GenerateCommentRequest):
|
|
| 256 |
|
| 257 |
|
| 258 |
@router.post("/generate", response_model=GenerateCommentResponse, dependencies=[Depends(_require_api_key)])
|
| 259 |
-
|
| 260 |
"""
|
| 261 |
Generate an AI-powered comment for a YouTube video.
|
| 262 |
Optimized for minimal API calls and token usage.
|
|
@@ -317,7 +319,7 @@ async def generate_youtube_comment(request: GenerateCommentRequest):
|
|
| 317 |
|
| 318 |
|
| 319 |
@router.post("/post", response_model=PostCommentResponse, dependencies=[Depends(_require_posting_key)])
|
| 320 |
-
|
| 321 |
"""
|
| 322 |
Post a comment to YouTube.
|
| 323 |
|
|
|
|
| 119 |
|
| 120 |
_COMMEND_API_KEY = os.getenv("COMMEND_API_KEY")
|
| 121 |
_COMMEND_POSTING_ENABLED = os.getenv("COMMEND_ENABLE_POSTING", "false").lower() == "true"
|
| 122 |
+
# Drafts are public (rate limited per visitor); set COMMEND_REQUIRE_AUTH=true to lock
|
| 123 |
+
# them behind COMMEND_API_KEY too. Posting always needs the key, see _require_posting_key.
|
| 124 |
+
_COMMEND_REQUIRE_AUTH = os.getenv("COMMEND_REQUIRE_AUTH", "false").lower() == "true"
|
| 125 |
|
| 126 |
# Simple in-memory rate limiter: IP -> list of timestamps
|
| 127 |
_rate_limit_store: dict[str, list[float]] = defaultdict(list)
|
|
|
|
| 234 |
|
| 235 |
|
| 236 |
@router.post("/video-details", response_model=VideoDetailsResponse, dependencies=[Depends(_rate_limit_only)])
|
| 237 |
+
def get_video_info(request: GenerateCommentRequest):
|
| 238 |
"""
|
| 239 |
Fetch video details without generating a comment.
|
| 240 |
Useful for preview before generation.
|
|
|
|
| 258 |
|
| 259 |
|
| 260 |
@router.post("/generate", response_model=GenerateCommentResponse, dependencies=[Depends(_require_api_key)])
|
| 261 |
+
def generate_youtube_comment(request: GenerateCommentRequest):
|
| 262 |
"""
|
| 263 |
Generate an AI-powered comment for a YouTube video.
|
| 264 |
Optimized for minimal API calls and token usage.
|
|
|
|
| 319 |
|
| 320 |
|
| 321 |
@router.post("/post", response_model=PostCommentResponse, dependencies=[Depends(_require_posting_key)])
|
| 322 |
+
def post_comment_to_youtube(request: PostCommentRequest):
|
| 323 |
"""
|
| 324 |
Post a comment to YouTube.
|
| 325 |
|
app/routes/data_processing.py
CHANGED
|
@@ -6,7 +6,7 @@ import time
|
|
| 6 |
import re
|
| 7 |
from collections import defaultdict
|
| 8 |
from fastapi import APIRouter, File, UploadFile, Form, HTTPException, Request, Depends, status
|
| 9 |
-
from fastapi.responses import
|
| 10 |
from pydantic import ValidationError
|
| 11 |
import json
|
| 12 |
import logging
|
|
@@ -15,6 +15,7 @@ from app.schemas import AudioAugmentationOptions, AudioConvertOptions, DatasetEn
|
|
| 15 |
from app.services.audio_processor import process_audio, convert_audio_format
|
| 16 |
from app.services.dataset_organizer import analyze_for_organization
|
| 17 |
from app.services.client_ip import client_ip as _client_ip
|
|
|
|
| 18 |
|
| 19 |
router = APIRouter(prefix="/api/process", tags=["Data Processing"])
|
| 20 |
logger = logging.getLogger(__name__)
|
|
@@ -111,12 +112,13 @@ async def process_audio_endpoint(
|
|
| 111 |
mix_content = await _read_capped(mix_file, MAX_PAYLOAD_BYTES) if mix_file is not None else None
|
| 112 |
|
| 113 |
# Process audio
|
| 114 |
-
processed_audio =
|
| 115 |
|
| 116 |
-
# Return as downloadable file
|
|
|
|
| 117 |
output_filename = f"processed_{safe_filename}.wav"
|
| 118 |
-
return
|
| 119 |
-
processed_audio,
|
| 120 |
media_type="audio/wav",
|
| 121 |
headers={"Content-Disposition": f"attachment; filename={output_filename}"}
|
| 122 |
)
|
|
@@ -186,12 +188,12 @@ async def convert_audio_endpoint(
|
|
| 186 |
chunks.append(chunk)
|
| 187 |
content = b"".join(chunks)
|
| 188 |
|
| 189 |
-
converted =
|
| 190 |
|
| 191 |
target = parsed_options.target_format
|
| 192 |
output_filename = f"{safe_filename}.{target}"
|
| 193 |
-
return
|
| 194 |
-
converted,
|
| 195 |
media_type=_CONVERT_MEDIA_TYPES[target],
|
| 196 |
headers={"Content-Disposition": f"attachment; filename={output_filename}"}
|
| 197 |
)
|
|
@@ -234,7 +236,7 @@ async def organize_audio_endpoint(file: UploadFile = File(...)):
|
|
| 234 |
chunks.append(chunk)
|
| 235 |
content = b"".join(chunks)
|
| 236 |
|
| 237 |
-
metadata =
|
| 238 |
return DatasetEntryMetadata(**metadata.to_dict())
|
| 239 |
|
| 240 |
except ValueError as e:
|
|
|
|
| 6 |
import re
|
| 7 |
from collections import defaultdict
|
| 8 |
from fastapi import APIRouter, File, UploadFile, Form, HTTPException, Request, Depends, status
|
| 9 |
+
from fastapi.responses import Response
|
| 10 |
from pydantic import ValidationError
|
| 11 |
import json
|
| 12 |
import logging
|
|
|
|
| 15 |
from app.services.audio_processor import process_audio, convert_audio_format
|
| 16 |
from app.services.dataset_organizer import analyze_for_organization
|
| 17 |
from app.services.client_ip import client_ip as _client_ip
|
| 18 |
+
from app.services.tool_gate import run_blocking
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/api/process", tags=["Data Processing"])
|
| 21 |
logger = logging.getLogger(__name__)
|
|
|
|
| 112 |
mix_content = await _read_capped(mix_file, MAX_PAYLOAD_BYTES) if mix_file is not None else None
|
| 113 |
|
| 114 |
# Process audio
|
| 115 |
+
processed_audio = await run_blocking(process_audio, content, parsed_options, mix_with_bytes=mix_content)
|
| 116 |
|
| 117 |
+
# Return as downloadable file. Sent as one body: iterating a BytesIO
|
| 118 |
+
# yields tiny "lines" at every 0x0A byte, which crawls over the proxy.
|
| 119 |
output_filename = f"processed_{safe_filename}.wav"
|
| 120 |
+
return Response(
|
| 121 |
+
content=processed_audio.getvalue(),
|
| 122 |
media_type="audio/wav",
|
| 123 |
headers={"Content-Disposition": f"attachment; filename={output_filename}"}
|
| 124 |
)
|
|
|
|
| 188 |
chunks.append(chunk)
|
| 189 |
content = b"".join(chunks)
|
| 190 |
|
| 191 |
+
converted = await run_blocking(convert_audio_format, content, parsed_options)
|
| 192 |
|
| 193 |
target = parsed_options.target_format
|
| 194 |
output_filename = f"{safe_filename}.{target}"
|
| 195 |
+
return Response(
|
| 196 |
+
content=converted.getvalue(),
|
| 197 |
media_type=_CONVERT_MEDIA_TYPES[target],
|
| 198 |
headers={"Content-Disposition": f"attachment; filename={output_filename}"}
|
| 199 |
)
|
|
|
|
| 236 |
chunks.append(chunk)
|
| 237 |
content = b"".join(chunks)
|
| 238 |
|
| 239 |
+
metadata = await run_blocking(analyze_for_organization, content)
|
| 240 |
return DatasetEntryMetadata(**metadata.to_dict())
|
| 241 |
|
| 242 |
except ValueError as e:
|
app/routes/dreams.py
CHANGED
|
@@ -8,6 +8,7 @@ import time
|
|
| 8 |
from collections import defaultdict
|
| 9 |
|
| 10 |
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
|
|
| 11 |
|
| 12 |
from app.schemas import DreamAnalysisRequest, DreamAnalysisResponse
|
| 13 |
from app.services.dream_analyzer import analyze_dream
|
|
@@ -54,13 +55,16 @@ async def analyze_dream_endpoint(payload: DreamAnalysisRequest) -> DreamAnalysis
|
|
| 54 |
"""
|
| 55 |
logger.info(f"Dream analysis request ({len(payload.dream_text)} chars, lang={payload.language})")
|
| 56 |
|
| 57 |
-
result, error =
|
| 58 |
|
| 59 |
if error is not None:
|
| 60 |
if "too short" in error.lower():
|
| 61 |
raise HTTPException(status_code=400, detail={"code": "dream_too_short", "message": error})
|
| 62 |
-
if "
|
| 63 |
raise HTTPException(status_code=503, detail={"code": "service_not_configured", "message": "Dream analysis is not configured."})
|
|
|
|
|
|
|
|
|
|
| 64 |
if "quota" in error.lower():
|
| 65 |
raise HTTPException(status_code=503, detail={"code": "service_unavailable", "message": error})
|
| 66 |
raise HTTPException(status_code=502, detail={"code": "analysis_failed", "message": error})
|
|
|
|
| 8 |
from collections import defaultdict
|
| 9 |
|
| 10 |
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
| 11 |
+
from starlette.concurrency import run_in_threadpool
|
| 12 |
|
| 13 |
from app.schemas import DreamAnalysisRequest, DreamAnalysisResponse
|
| 14 |
from app.services.dream_analyzer import analyze_dream
|
|
|
|
| 55 |
"""
|
| 56 |
logger.info(f"Dream analysis request ({len(payload.dream_text)} chars, lang={payload.language})")
|
| 57 |
|
| 58 |
+
result, error = await run_in_threadpool(analyze_dream, payload.dream_text, payload.language)
|
| 59 |
|
| 60 |
if error is not None:
|
| 61 |
if "too short" in error.lower():
|
| 62 |
raise HTTPException(status_code=400, detail={"code": "dream_too_short", "message": error})
|
| 63 |
+
if "not configured" in error.lower():
|
| 64 |
raise HTTPException(status_code=503, detail={"code": "service_not_configured", "message": "Dream analysis is not configured."})
|
| 65 |
+
if "api key" in error.lower():
|
| 66 |
+
# A key is set but Gemini refuses it: the owner has to replace it.
|
| 67 |
+
raise HTTPException(status_code=503, detail={"code": "service_unavailable", "message": "Dream analysis is unavailable right now."})
|
| 68 |
if "quota" in error.lower():
|
| 69 |
raise HTTPException(status_code=503, detail={"code": "service_unavailable", "message": error})
|
| 70 |
raise HTTPException(status_code=502, detail={"code": "analysis_failed", "message": error})
|
app/routes/remix.py
CHANGED
|
@@ -8,13 +8,14 @@ import time
|
|
| 8 |
from collections import defaultdict
|
| 9 |
|
| 10 |
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status
|
| 11 |
-
from fastapi.responses import
|
| 12 |
from pydantic import ValidationError
|
| 13 |
|
| 14 |
from app.schemas import MultitrackAnalysis, MultitrackOptions, RemixAnalysis, RemixOptions
|
| 15 |
from app.services.multitrack_mixer import MAX_CHANNELS, MIN_CHANNELS, mix_tracks
|
| 16 |
from app.services.remix_engine import build_remix
|
| 17 |
from app.services.client_ip import client_ip as _client_ip
|
|
|
|
| 18 |
|
| 19 |
router = APIRouter(prefix="/api/remix", tags=["Creator Studio"])
|
| 20 |
logger = logging.getLogger(__name__)
|
|
@@ -101,15 +102,15 @@ async def remix_blend_endpoint(
|
|
| 101 |
content_a = await _read_capped(track_a, MAX_PAYLOAD_BYTES)
|
| 102 |
content_b = await _read_capped(track_b, MAX_PAYLOAD_BYTES)
|
| 103 |
|
| 104 |
-
result =
|
| 105 |
|
| 106 |
# Serialize via the Pydantic model so the header uses the same
|
| 107 |
# camelCase field names the frontend's RemixAnalysis type expects —
|
| 108 |
# result.analysis itself is a plain snake_case dict.
|
| 109 |
analysis_model = RemixAnalysis(**result.analysis)
|
| 110 |
analysis_json = analysis_model.model_dump_json(by_alias=True)
|
| 111 |
-
return
|
| 112 |
-
result.audio,
|
| 113 |
media_type="audio/wav",
|
| 114 |
headers={
|
| 115 |
"Content-Disposition": "attachment; filename=crowncode-remix.wav",
|
|
@@ -167,13 +168,13 @@ async def multitrack_mix_endpoint(
|
|
| 167 |
try:
|
| 168 |
contents = [await _read_capped(f, MAX_PAYLOAD_BYTES) for f in tracks]
|
| 169 |
|
| 170 |
-
result =
|
| 171 |
|
| 172 |
# Same camelCase-via-Pydantic serialization as the /blend endpoint.
|
| 173 |
analysis_model = MultitrackAnalysis(**result.analysis)
|
| 174 |
analysis_json = analysis_model.model_dump_json(by_alias=True)
|
| 175 |
-
return
|
| 176 |
-
result.audio,
|
| 177 |
media_type="audio/wav",
|
| 178 |
headers={
|
| 179 |
"Content-Disposition": "attachment; filename=crowncode-multitrack-mix.wav",
|
|
|
|
| 8 |
from collections import defaultdict
|
| 9 |
|
| 10 |
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, status
|
| 11 |
+
from fastapi.responses import Response
|
| 12 |
from pydantic import ValidationError
|
| 13 |
|
| 14 |
from app.schemas import MultitrackAnalysis, MultitrackOptions, RemixAnalysis, RemixOptions
|
| 15 |
from app.services.multitrack_mixer import MAX_CHANNELS, MIN_CHANNELS, mix_tracks
|
| 16 |
from app.services.remix_engine import build_remix
|
| 17 |
from app.services.client_ip import client_ip as _client_ip
|
| 18 |
+
from app.services.tool_gate import run_blocking
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/api/remix", tags=["Creator Studio"])
|
| 21 |
logger = logging.getLogger(__name__)
|
|
|
|
| 102 |
content_a = await _read_capped(track_a, MAX_PAYLOAD_BYTES)
|
| 103 |
content_b = await _read_capped(track_b, MAX_PAYLOAD_BYTES)
|
| 104 |
|
| 105 |
+
result = await run_blocking(build_remix, content_a, content_b, parsed_options)
|
| 106 |
|
| 107 |
# Serialize via the Pydantic model so the header uses the same
|
| 108 |
# camelCase field names the frontend's RemixAnalysis type expects —
|
| 109 |
# result.analysis itself is a plain snake_case dict.
|
| 110 |
analysis_model = RemixAnalysis(**result.analysis)
|
| 111 |
analysis_json = analysis_model.model_dump_json(by_alias=True)
|
| 112 |
+
return Response(
|
| 113 |
+
content=result.audio.getvalue(),
|
| 114 |
media_type="audio/wav",
|
| 115 |
headers={
|
| 116 |
"Content-Disposition": "attachment; filename=crowncode-remix.wav",
|
|
|
|
| 168 |
try:
|
| 169 |
contents = [await _read_capped(f, MAX_PAYLOAD_BYTES) for f in tracks]
|
| 170 |
|
| 171 |
+
result = await run_blocking(mix_tracks, contents, parsed_options)
|
| 172 |
|
| 173 |
# Same camelCase-via-Pydantic serialization as the /blend endpoint.
|
| 174 |
analysis_model = MultitrackAnalysis(**result.analysis)
|
| 175 |
analysis_json = analysis_model.model_dump_json(by_alias=True)
|
| 176 |
+
return Response(
|
| 177 |
+
content=result.audio.getvalue(),
|
| 178 |
media_type="audio/wav",
|
| 179 |
headers={
|
| 180 |
"Content-Disposition": "attachment; filename=crowncode-multitrack-mix.wav",
|
app/services/dream_analyzer.py
CHANGED
|
@@ -27,6 +27,10 @@ _client = None
|
|
| 27 |
_MAX_DREAM_CHARS = 4000
|
| 28 |
_MIN_DREAM_CHARS = 10
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def _get_client():
|
| 32 |
global _client
|
|
@@ -35,7 +39,7 @@ def _get_client():
|
|
| 35 |
|
| 36 |
api_key = os.getenv("DREAMS_GEMINI_API_KEY") or os.getenv("COMMEND_GEMINI_API_KEY")
|
| 37 |
if not api_key:
|
| 38 |
-
raise ValueError("DREAMS_GEMINI_API_KEY
|
| 39 |
|
| 40 |
try:
|
| 41 |
_client = genai.Client(api_key=api_key)
|
|
@@ -97,10 +101,19 @@ Dream description:
|
|
| 97 |
|
| 98 |
JSON:"""
|
| 99 |
|
| 100 |
-
response =
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
raw = response.text.strip() if response.text else ""
|
| 106 |
parsed = _extract_json(raw)
|
|
@@ -132,7 +145,10 @@ JSON:"""
|
|
| 132 |
# from _get_client() reads "..._api_key required" (underscore), and
|
| 133 |
# Gemini's own errors tend to read "API key not valid" (space), so
|
| 134 |
# a plain substring check on either form alone misses the other.
|
|
|
|
|
|
|
| 135 |
if "api key" in err or "api_key" in err or "apikey" in err:
|
|
|
|
| 136 |
return None, "Invalid API key"
|
| 137 |
if "quota" in err or "limit" in err or "resource" in err:
|
| 138 |
return None, "API quota exceeded"
|
|
|
|
| 27 |
_MAX_DREAM_CHARS = 4000
|
| 28 |
_MIN_DREAM_CHARS = 10
|
| 29 |
|
| 30 |
+
# Tried in order; a model Google has retired falls through to the next one.
|
| 31 |
+
_MODELS = [m for m in (os.getenv("DREAMS_GEMINI_MODEL"), "gemini-2.5-flash-lite", "gemini-2.5-flash") if m]
|
| 32 |
+
_MODEL_GONE = ("not found", "no longer available", "deprecated", "is not supported", "404")
|
| 33 |
+
|
| 34 |
|
| 35 |
def _get_client():
|
| 36 |
global _client
|
|
|
|
| 39 |
|
| 40 |
api_key = os.getenv("DREAMS_GEMINI_API_KEY") or os.getenv("COMMEND_GEMINI_API_KEY")
|
| 41 |
if not api_key:
|
| 42 |
+
raise ValueError("Dream analysis is not configured: set DREAMS_GEMINI_API_KEY or COMMEND_GEMINI_API_KEY")
|
| 43 |
|
| 44 |
try:
|
| 45 |
_client = genai.Client(api_key=api_key)
|
|
|
|
| 101 |
|
| 102 |
JSON:"""
|
| 103 |
|
| 104 |
+
response = None
|
| 105 |
+
last_error: Optional[Exception] = None
|
| 106 |
+
for model in _MODELS:
|
| 107 |
+
try:
|
| 108 |
+
response = client.models.generate_content(model=model, contents=prompt)
|
| 109 |
+
break
|
| 110 |
+
except Exception as e: # noqa: BLE001 - classified below
|
| 111 |
+
last_error = e
|
| 112 |
+
if not any(marker in str(e).lower() for marker in _MODEL_GONE):
|
| 113 |
+
raise
|
| 114 |
+
logger.warning(f"Gemini model {model} unavailable, trying the next one: {e}")
|
| 115 |
+
if response is None:
|
| 116 |
+
raise last_error or RuntimeError("no Gemini model answered")
|
| 117 |
|
| 118 |
raw = response.text.strip() if response.text else ""
|
| 119 |
parsed = _extract_json(raw)
|
|
|
|
| 145 |
# from _get_client() reads "..._api_key required" (underscore), and
|
| 146 |
# Gemini's own errors tend to read "API key not valid" (space), so
|
| 147 |
# a plain substring check on either form alone misses the other.
|
| 148 |
+
if "not configured" in err:
|
| 149 |
+
return None, "Dream analysis is not configured"
|
| 150 |
if "api key" in err or "api_key" in err or "apikey" in err:
|
| 151 |
+
logger.error("Gemini refused the configured API key; replace DREAMS_GEMINI_API_KEY / COMMEND_GEMINI_API_KEY")
|
| 152 |
return None, "Invalid API key"
|
| 153 |
if "quota" in err or "limit" in err or "resource" in err:
|
| 154 |
return None, "API quota exceeded"
|
app/services/tool_gate.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Keeps the Creator Studio and ML Toolkit audio work off the event loop.
|
| 2 |
+
|
| 3 |
+
Remixing, mixing, converting and tagging audio are CPU-bound librosa calls. Run
|
| 4 |
+
inline in an async handler they freeze the whole server (health checks, AURIS
|
| 5 |
+
polling, other downloads) until they finish. They go to a worker thread
|
| 6 |
+
instead, and at most TOOLS_CPU_SLOTS of them run at once so two visitors'
|
| 7 |
+
jobs don't starve each other and the AURIS analysis on the same CPU.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import asyncio
|
| 13 |
+
import os
|
| 14 |
+
from contextlib import asynccontextmanager
|
| 15 |
+
from typing import Any, AsyncIterator, Callable, Optional, TypeVar
|
| 16 |
+
|
| 17 |
+
from fastapi import HTTPException, status
|
| 18 |
+
from starlette.concurrency import run_in_threadpool
|
| 19 |
+
|
| 20 |
+
T = TypeVar("T")
|
| 21 |
+
|
| 22 |
+
TOOL_SLOTS = max(1, int(os.getenv("TOOLS_CPU_SLOTS", "1")))
|
| 23 |
+
# Jobs allowed to wait for a slot; past that the visitor is told to come back.
|
| 24 |
+
MAX_WAITING = max(1, int(os.getenv("TOOLS_MAX_WAITING", "6")))
|
| 25 |
+
|
| 26 |
+
_semaphore: Optional[asyncio.Semaphore] = None
|
| 27 |
+
_semaphore_loop: Optional[asyncio.AbstractEventLoop] = None
|
| 28 |
+
_waiting = 0
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def waiting() -> int:
|
| 32 |
+
return _waiting
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@asynccontextmanager
|
| 36 |
+
async def tool_slot() -> AsyncIterator[None]:
|
| 37 |
+
global _semaphore, _semaphore_loop, _waiting
|
| 38 |
+
loop = asyncio.get_running_loop()
|
| 39 |
+
if _semaphore is None or _semaphore_loop is not loop:
|
| 40 |
+
# One per event loop: a semaphore must not be shared across loops (tests start several).
|
| 41 |
+
_semaphore, _semaphore_loop, _waiting = asyncio.Semaphore(TOOL_SLOTS), loop, 0
|
| 42 |
+
if _waiting >= MAX_WAITING:
|
| 43 |
+
raise HTTPException(
|
| 44 |
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
| 45 |
+
detail={"code": "server_busy", "message": "Too many audio jobs are waiting. Try again in a minute."},
|
| 46 |
+
headers={"Retry-After": "30"},
|
| 47 |
+
)
|
| 48 |
+
_waiting += 1
|
| 49 |
+
try:
|
| 50 |
+
await _semaphore.acquire()
|
| 51 |
+
finally:
|
| 52 |
+
_waiting -= 1
|
| 53 |
+
try:
|
| 54 |
+
yield
|
| 55 |
+
finally:
|
| 56 |
+
_semaphore.release()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
async def run_blocking(fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
|
| 60 |
+
"""Run a CPU-bound function in a worker thread, waiting for a free slot first."""
|
| 61 |
+
async with tool_slot():
|
| 62 |
+
return await run_in_threadpool(fn, *args, **kwargs)
|
tests/test_tool_gate.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audio tools run off the event loop, one at a time, and the dream errors reach the page unchanged."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import io
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pytest
|
| 13 |
+
import soundfile as sf
|
| 14 |
+
from fastapi import FastAPI, HTTPException
|
| 15 |
+
from fastapi.testclient import TestClient
|
| 16 |
+
|
| 17 |
+
from app.routes import dreams as dreams_module
|
| 18 |
+
from app.routes.data_processing import router as process_router
|
| 19 |
+
from app.routes.dreams import router as dreams_router
|
| 20 |
+
from app.routes.remix import router as remix_router
|
| 21 |
+
from app.services import tool_gate
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.fixture(autouse=True)
|
| 25 |
+
def fresh_gate(monkeypatch):
|
| 26 |
+
monkeypatch.setattr(tool_gate, "_semaphore", None)
|
| 27 |
+
monkeypatch.setattr(tool_gate, "_semaphore_loop", None)
|
| 28 |
+
monkeypatch.setattr(tool_gate, "_waiting", 0)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def wav(seconds: float = 2.0, freq: float = 220.0, sr: int = 22050) -> bytes:
|
| 32 |
+
t = np.arange(int(seconds * sr)) / sr
|
| 33 |
+
buf = io.BytesIO()
|
| 34 |
+
sf.write(buf, (0.3 * np.sin(2 * np.pi * freq * t)).astype(np.float32), sr, format="WAV")
|
| 35 |
+
return buf.getvalue()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ── the gate ─────────────────────────────────────────────────────────
|
| 39 |
+
|
| 40 |
+
def test_work_runs_in_a_worker_thread_not_on_the_loop() -> None:
|
| 41 |
+
async def scenario():
|
| 42 |
+
loop_thread = threading.get_ident()
|
| 43 |
+
return loop_thread, await tool_gate.run_blocking(threading.get_ident)
|
| 44 |
+
|
| 45 |
+
loop_thread, worker_thread = asyncio.run(scenario())
|
| 46 |
+
assert worker_thread != loop_thread
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_the_loop_stays_responsive_while_a_job_runs() -> None:
|
| 50 |
+
async def scenario():
|
| 51 |
+
ticks = 0
|
| 52 |
+
|
| 53 |
+
async def heartbeat():
|
| 54 |
+
nonlocal ticks
|
| 55 |
+
while True:
|
| 56 |
+
await asyncio.sleep(0.02)
|
| 57 |
+
ticks += 1
|
| 58 |
+
|
| 59 |
+
beat = asyncio.create_task(heartbeat())
|
| 60 |
+
await tool_gate.run_blocking(time.sleep, 0.3)
|
| 61 |
+
beat.cancel()
|
| 62 |
+
return ticks
|
| 63 |
+
|
| 64 |
+
assert asyncio.run(scenario()) >= 5
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_one_job_at_a_time_by_default(monkeypatch) -> None:
|
| 68 |
+
monkeypatch.setattr(tool_gate, "TOOL_SLOTS", 1)
|
| 69 |
+
running = {"now": 0, "peak": 0}
|
| 70 |
+
lock = threading.Lock()
|
| 71 |
+
|
| 72 |
+
def job():
|
| 73 |
+
with lock:
|
| 74 |
+
running["now"] += 1
|
| 75 |
+
running["peak"] = max(running["peak"], running["now"])
|
| 76 |
+
time.sleep(0.1)
|
| 77 |
+
with lock:
|
| 78 |
+
running["now"] -= 1
|
| 79 |
+
|
| 80 |
+
async def scenario():
|
| 81 |
+
await asyncio.gather(*(tool_gate.run_blocking(job) for _ in range(3)))
|
| 82 |
+
|
| 83 |
+
asyncio.run(scenario())
|
| 84 |
+
assert running["peak"] == 1
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_a_full_queue_says_busy_instead_of_piling_up(monkeypatch) -> None:
|
| 88 |
+
monkeypatch.setattr(tool_gate, "MAX_WAITING", 2)
|
| 89 |
+
|
| 90 |
+
async def scenario():
|
| 91 |
+
# One job holds the slot and two wait for it; a fourth has nowhere to go.
|
| 92 |
+
jobs = [asyncio.create_task(tool_gate.run_blocking(time.sleep, 0.3)) for _ in range(3)]
|
| 93 |
+
await asyncio.sleep(0.05)
|
| 94 |
+
with pytest.raises(HTTPException) as busy:
|
| 95 |
+
await tool_gate.run_blocking(time.sleep, 0)
|
| 96 |
+
await asyncio.gather(*jobs)
|
| 97 |
+
return busy.value
|
| 98 |
+
|
| 99 |
+
err = asyncio.run(scenario())
|
| 100 |
+
assert err.status_code == 503
|
| 101 |
+
assert err.detail["code"] == "server_busy"
|
| 102 |
+
assert err.headers["Retry-After"] == "30"
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ── routes ───────────────────────────────────────────────────────────
|
| 106 |
+
|
| 107 |
+
@pytest.fixture
|
| 108 |
+
def tools_client() -> TestClient:
|
| 109 |
+
app = FastAPI()
|
| 110 |
+
app.include_router(process_router)
|
| 111 |
+
app.include_router(remix_router)
|
| 112 |
+
return TestClient(app)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_convert_returns_the_file_in_one_body(tools_client) -> None:
|
| 116 |
+
response = tools_client.post(
|
| 117 |
+
"/api/process/audio/convert",
|
| 118 |
+
files={"file": ("tone.wav", wav(), "audio/wav")},
|
| 119 |
+
data={"options": '{"targetFormat": "flac"}'},
|
| 120 |
+
)
|
| 121 |
+
assert response.status_code == 200
|
| 122 |
+
assert response.headers["content-type"] == "audio/flac"
|
| 123 |
+
assert int(response.headers["content-length"]) == len(response.content) > 1000
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_organize_reads_the_clip(tools_client) -> None:
|
| 127 |
+
response = tools_client.post("/api/process/audio/organize", files={"file": ("tone.wav", wav(), "audio/wav")})
|
| 128 |
+
assert response.status_code == 200
|
| 129 |
+
assert response.json()["durationSec"] == pytest.approx(2.0, abs=0.1)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_blend_returns_audio_and_its_analysis_header(tools_client) -> None:
|
| 133 |
+
response = tools_client.post(
|
| 134 |
+
"/api/remix/blend",
|
| 135 |
+
files={"track_a": ("a.wav", wav(freq=220), "audio/wav"), "track_b": ("b.wav", wav(freq=330), "audio/wav")},
|
| 136 |
+
data={"options": "{}"},
|
| 137 |
+
)
|
| 138 |
+
assert response.status_code == 200
|
| 139 |
+
assert response.content[:4] == b"RIFF"
|
| 140 |
+
assert int(response.headers["content-length"]) == len(response.content)
|
| 141 |
+
assert "outputDurationSec" in response.headers["x-remix-analysis"]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_multitrack_needs_two_tracks(tools_client) -> None:
|
| 145 |
+
response = tools_client.post("/api/remix/multitrack", files=[("tracks", ("a.wav", wav(), "audio/wav"))], data={"options": "{}"})
|
| 146 |
+
assert response.status_code == 400
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ── dreams ───────────────────────────────────────────────────────────
|
| 150 |
+
|
| 151 |
+
@pytest.fixture
|
| 152 |
+
def dreams_client(monkeypatch) -> TestClient:
|
| 153 |
+
monkeypatch.setattr(dreams_module, "_rate_store", defaultdict(list))
|
| 154 |
+
app = FastAPI()
|
| 155 |
+
app.include_router(dreams_router)
|
| 156 |
+
return TestClient(app)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def post_dream(client: TestClient):
|
| 160 |
+
return client.post("/api/dreams/analyze", json={"dreamText": "a dream that is long enough", "language": "English"})
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@pytest.mark.parametrize("error,status,code", [
|
| 164 |
+
("Dream analysis is not configured", 503, "service_not_configured"),
|
| 165 |
+
("Invalid API key", 503, "service_unavailable"),
|
| 166 |
+
("API quota exceeded", 503, "service_unavailable"),
|
| 167 |
+
("Analysis produced an unexpected response format.", 502, "analysis_failed"),
|
| 168 |
+
("Dream description is too short to analyze.", 400, "dream_too_short"),
|
| 169 |
+
])
|
| 170 |
+
def test_dream_errors_map_to_distinct_codes(dreams_client, monkeypatch, error, status, code) -> None:
|
| 171 |
+
monkeypatch.setattr(dreams_module, "analyze_dream", lambda text, language: (None, error))
|
| 172 |
+
response = post_dream(dreams_client)
|
| 173 |
+
assert response.status_code == status
|
| 174 |
+
assert response.json()["detail"]["code"] == code
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_a_good_reading_comes_back(dreams_client, monkeypatch) -> None:
|
| 178 |
+
reading = {"emotions": ["fear"], "themes": ["falling"], "symbols": ["moon"], "interpretation": "A reading.", "lucidityIndicator": False}
|
| 179 |
+
monkeypatch.setattr(dreams_module, "analyze_dream", lambda text, language: (reading, None))
|
| 180 |
+
response = post_dream(dreams_client)
|
| 181 |
+
assert response.status_code == 200
|
| 182 |
+
assert response.json()["interpretation"] == "A reading."
|