Skip to content

Commit 9a13d4c

Browse files
authored
Merge pull request #404 from tonyjohnvan/fix/cors-browser-frontend
(fix)Add CORS support for direct open browser-based frontends (studio.html)
2 parents 2b36f21 + e34ec18 commit 9a13d4c

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

acestep/api_server.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
load_dotenv = None # type: ignore
4242

4343
from fastapi import FastAPI, HTTPException, Request, Depends, Header
44+
from fastapi.middleware.cors import CORSMiddleware
4445
from pydantic import BaseModel, Field
4546
from starlette.datastructures import UploadFile as StarletteUploadFile
4647

@@ -2155,6 +2156,16 @@ async def _job_store_cleanup_worker() -> None:
21552156

21562157
app = FastAPI(title="ACE-Step API", version="1.0", lifespan=lifespan)
21572158

2159+
# Enable CORS for browser-based frontends (e.g. studio.html opened via file://)
2160+
# Restricted to localhost origins and the "null" origin (file:// protocol)
2161+
app.add_middleware(
2162+
CORSMiddleware,
2163+
allow_origins=["null", "http://localhost", "http://127.0.0.1"],
2164+
allow_origin_regex=r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$",
2165+
allow_methods=["GET", "POST", "OPTIONS"],
2166+
allow_headers=["Content-Type", "Authorization"],
2167+
)
2168+
21582169
# Mount OpenRouter-compatible endpoints (/v1/chat/completions, /v1/models)
21592170
from acestep.openrouter_adapter import create_openrouter_router
21602171
openrouter_router = create_openrouter_router(lambda: app.state)

acestep/gradio_ui/api_routes.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from uuid import uuid4
1111

1212
from fastapi import APIRouter, HTTPException, Request, Depends, Header
13+
from fastapi.middleware.cors import CORSMiddleware
1314
from fastapi.responses import FileResponse
1415

1516
# Global results directory inside project root
@@ -512,6 +513,38 @@ def to_bool(val, default=False):
512513
raise HTTPException(status_code=500, detail=str(e))
513514

514515

516+
# Origins that are expected to call the API:
517+
# - "null" → studio.html opened via file:// protocol
518+
# - http://localhost:* → local dev servers / Gradio UI
519+
# - http://127.0.0.1:* → same, numeric form
520+
_CORS_KWARGS = dict(
521+
allow_origins=["null", "http://localhost", "http://127.0.0.1"],
522+
allow_origin_regex=r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$",
523+
allow_methods=["GET", "POST", "OPTIONS"],
524+
allow_headers=["Content-Type", "Authorization"],
525+
)
526+
527+
528+
def _add_cors_middleware(app):
529+
"""Add CORS middleware so browser-based frontends (e.g. studio.html via file://) can call the API."""
530+
app.add_middleware(CORSMiddleware, **_CORS_KWARGS)
531+
532+
533+
def _add_cors_middleware_post_launch(app):
534+
"""Wrap an already-started app's middleware stack with CORS.
535+
536+
``add_middleware`` raises after Starlette has started, so we patch the
537+
compiled middleware stack directly instead.
538+
"""
539+
from starlette.middleware.cors import CORSMiddleware as _CORSImpl
540+
541+
if app.middleware_stack is not None:
542+
app.middleware_stack = _CORSImpl(app=app.middleware_stack, **_CORS_KWARGS)
543+
else:
544+
# App hasn't built its stack yet – safe to use the normal path
545+
_add_cors_middleware(app)
546+
547+
515548
def setup_api_routes_to_app(app, dit_handler, llm_handler, api_key: Optional[str] = None):
516549
"""
517550
Mount API routes to a FastAPI application (for use with gr.mount_gradio_app)
@@ -523,6 +556,7 @@ def setup_api_routes_to_app(app, dit_handler, llm_handler, api_key: Optional[str
523556
api_key: Optional API key for authentication
524557
"""
525558
set_api_key(api_key)
559+
_add_cors_middleware(app)
526560
app.state.dit_handler = dit_handler
527561
app.state.llm_handler = llm_handler
528562
app.include_router(router)
@@ -540,6 +574,7 @@ def setup_api_routes(demo, dit_handler, llm_handler, api_key: Optional[str] = No
540574
"""
541575
set_api_key(api_key)
542576
app = demo.app
577+
_add_cors_middleware_post_launch(app)
543578
app.state.dit_handler = dit_handler
544579
app.state.llm_handler = llm_handler
545580
app.include_router(router)

0 commit comments

Comments
 (0)