Spaces:
Running on Zero
Running on Zero
File size: 4,427 Bytes
e9017a4 | 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 | """FastAPI Server for Qwen-Image-2.1 Viggle Turbo.
Serves the modern Shadcn/Tailwind pure HTML frontend at '/'
and connects to Qwen AI diffusion logic via clean REST APIs.
"""
import os
import io
import json
import base64
import time
import random
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from PIL import Image
# Ensure preview mode environment is preserved if set
import app
fastapi_app = FastAPI(title="Qwen Studio 2.1 API")
# Enable CORS
fastapi_app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
INDEX_HTML_PATH = os.path.join(CURRENT_DIR, "index.html")
@fastapi_app.get("/", response_class=HTMLResponse)
async def serve_index():
if os.path.exists(INDEX_HTML_PATH):
with open(INDEX_HTML_PATH, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read())
return HTMLResponse("<h1>index.html not found</h1>", status_code=404)
@fastapi_app.get("/api/health")
async def health_check():
return {
"status": "ok",
"preview_mode": bool(app.pipe is None or app.IS_PREVIEW),
"model_id": app.MODEL_ID,
"default_lora": app.DEFAULT_LORA
}
@fastapi_app.get("/api/search-loras")
async def api_search_loras(q: str = ""):
choices = app.search_hf_loras(q)
models = []
for item in choices:
if isinstance(item, tuple):
models.append({"repo_id": item[1], "name": item[0]})
elif isinstance(item, str):
models.append({"repo_id": item, "name": item})
return {"models": models}
@fastapi_app.get("/api/repo-files")
async def api_repo_files(repo: str = ""):
files = app.fetch_repo_safetensors(repo)
return {"files": files}
@fastapi_app.post("/api/generate")
async def api_generate(request: Request):
try:
data = await request.json()
prompt = data.get("prompt", "")
mode = data.get("mode", "Text to Image")
lora_adapter = data.get("lora_adapter", app.DEFAULT_LORA)
lora_strength = float(data.get("lora_strength", 1.0))
custom_repo = data.get("custom_repo", "")
custom_file = data.get("custom_file", "")
aspect_ratio = data.get("aspect_ratio", app.AUTO)
steps = int(data.get("steps", 6))
seed = int(data.get("seed", 42))
randomize_seed = bool(data.get("randomize_seed", True))
ref_image_1 = None
ref_image_2 = None
if data.get("ref_image_1_b64"):
b64_data = data["ref_image_1_b64"].split(",")[-1]
ref_image_1 = Image.open(io.BytesIO(base64.b64decode(b64_data)))
if data.get("ref_image_2_b64"):
b64_data = data["ref_image_2_b64"].split(",")[-1]
ref_image_2 = Image.open(io.BytesIO(base64.b64decode(b64_data)))
# Invoke core generate function
result_img, dl_path, status_str, used_prompt, idb_payload = app.generate(
prompt=prompt,
mode=mode,
ref_image_1=ref_image_1,
ref_image_2=ref_image_2,
lora_adapter=lora_adapter,
lora_strength=lora_strength,
custom_repo=custom_repo,
custom_file=custom_file,
aspect_ratio=aspect_ratio,
steps=steps,
seed=seed,
randomize_seed=randomize_seed,
)
# Convert image to base64 PNG data URL
buf = io.BytesIO()
result_img.save(buf, format="PNG")
img_b64 = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("utf-8")
parsed_idb = json.loads(idb_payload)
return {
"image_b64": img_b64,
"status": status_str,
"prompt": used_prompt,
"seed": parsed_idb.get("seed"),
"steps": steps,
"width": result_img.width,
"height": result_img.height,
}
except Exception as e:
return JSONResponse(status_code=400, content={"error": str(e)})
if __name__ == "__main__":
print("=" * 70)
print(" QWEN STUDIO 2.1 - PURE HTML / FASTAPI SERVER")
print(" Serving Pure HTML Frontend at http://127.0.0.1:7860")
print("=" * 70)
uvicorn.run(fastapi_app, host="127.0.0.1", port=7860)
|