Spaces:
Sleeping
Sleeping
Download backend/app/api/flux2.py from tntgroup/website_content: direct link, hf CLI and curl.
- Browser
- Download file 9.92 kB
-
https://huggingface.co/spaces/tntgroup/website_content/resolve/main/backend/app/api/flux2.py
- Command line
-
hf download hf://spaces/tntgroup/website_content/backend/app/api/flux2.py
-
curl -L -o flux2.py https://huggingface.co/spaces/tntgroup/website_content/resolve/main/backend/app/api/flux2.py
9.92 kB
| from __future__ import annotations | |
| import os | |
| import threading | |
| import time | |
| import uuid | |
| from pathlib import Path | |
| from typing import Any | |
| import httpx | |
| from fastapi import APIRouter, HTTPException | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel | |
| from gradio_client import Client, handle_file | |
| from ..core.bg import submit_bg | |
| from ..core.reqctx import get_ctx | |
| from ..services.analytics import track as tracking | |
| WANGP_URL = "https://00114dcf4c286c050a.gradio.live/" | |
| OUTPUT_DIR = Path(__file__).resolve().parent.parent / "flux2_outputs" | |
| OUTPUT_DIR.mkdir(exist_ok=True) | |
| _client = None | |
| _client_lock = threading.Lock() | |
| def _get_client(): | |
| global _client | |
| if _client is not None: | |
| return _client | |
| with _client_lock: | |
| if _client is not None: | |
| return _client | |
| try: | |
| _client = Client(WANGP_URL) | |
| except Exception as e: | |
| raise RuntimeError(f"Cannot connect to Wangp API at {WANGP_URL}: {e}") | |
| return _client | |
| DEFAULT_VIDEO = { | |
| "video": handle_file( | |
| "https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4" | |
| ) | |
| } | |
| DEFAULT_IMAGE = handle_file( | |
| "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png" | |
| ) | |
| DEFAULT_AUDIO = handle_file( | |
| "https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav" | |
| ) | |
| DEFAULT_FILE = handle_file( | |
| "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" | |
| ) | |
| _tasks: dict[str, dict[str, Any]] = {} | |
| _tasks_lock = threading.Lock() | |
| router = APIRouter(prefix="/api/flux2", tags=["flux2"]) | |
| class GenRequest(BaseModel): | |
| prompt: str | |
| negative_prompt: str = "" | |
| resolution: str = "1024x1024" | |
| num_inference_steps: int = 4 | |
| guidance_scale: float = 5.0 | |
| seed: int = -1 | |
| batch_size: int = 1 | |
| def _extract_images(result) -> list: | |
| if not result: | |
| return [] | |
| if isinstance(result, (list, tuple)): | |
| for item in result: | |
| if isinstance(item, list): | |
| return item | |
| if isinstance(item, dict) and ("image" in item or "video" in item): | |
| return [item] | |
| if all(isinstance(x, dict) for x in result if x): | |
| return result | |
| return [] | |
| def _download_image(img_info: Any, dest: Path): | |
| if isinstance(img_info, dict): | |
| img = img_info.get("image", img_info.get("video", {})) | |
| if isinstance(img, dict): | |
| path = img.get("path", img.get("url", "")) | |
| else: | |
| path = str(img) if img else "" | |
| else: | |
| path = str(img_info) | |
| if not path: | |
| raise ValueError("No image path found") | |
| if path.startswith("/"): | |
| url = f"{WANGP_URL.rstrip('/')}/file={path.lstrip('/')}" | |
| elif path.startswith("http"): | |
| url = path | |
| else: | |
| url = f"{WANGP_URL.rstrip('/')}/file={path}" | |
| with httpx.Client(timeout=120.0, follow_redirects=True) as c: | |
| resp = c.get(url) | |
| resp.raise_for_status() | |
| dest.write_bytes(resp.content) | |
| def _generate(task_id: str, params: dict, ctx: dict | None = None): | |
| ctx = ctx or {} | |
| started = time.time() | |
| tracking.emit("job_started", ctx, job_id=task_id, kind="flux2") | |
| try: | |
| with _tasks_lock: | |
| _tasks[task_id] = {"status": "processing"} | |
| result = _get_client().predict( | |
| prompt=params["prompt"], | |
| negative_prompt=params.get("negative_prompt", ""), | |
| alt_prompt="", | |
| resolution=params.get("resolution", "1024x1024"), | |
| video_length=81, | |
| duration_seconds=0, | |
| pause_seconds=0, | |
| batch_size=params.get("batch_size", 1), | |
| seed=params.get("seed", -1), | |
| num_inference_steps=params.get("num_inference_steps", 4), | |
| guidance_scale=params.get("guidance_scale", 5), | |
| guidance2_scale=5, | |
| guidance3_scale=5, | |
| guidance_phases="1", | |
| model_switch_phase="1", | |
| flow_shift=5, | |
| sample_solver="", | |
| temperature=0.8, | |
| top_p=0.9, | |
| top_k=50, | |
| loras_choices=[], | |
| loras_multipliers="", | |
| image_refs=[], | |
| image_refs_relative_size=50, | |
| remove_background_images_ref="0", | |
| frames_positions="", | |
| image_prompt_type="", | |
| image_start=[], | |
| image_end=[], | |
| image_guide=DEFAULT_IMAGE, | |
| image_mask=DEFAULT_IMAGE, | |
| control_net_weight=1, | |
| control_net_weight2=1, | |
| denoising_strength=1, | |
| masking_strength=0.25, | |
| mask_expand=0, | |
| model_mode="0", | |
| prompt_enhancer="", | |
| film_grain_intensity=0, | |
| film_grain_saturation=0.5, | |
| temporal_upsampling="", | |
| spatial_upsampling="", | |
| video_guide_outpainting="#", | |
| video_guide_outpainting_ratio="", | |
| override_profile="-1", | |
| override_attention="auto", | |
| alt_guidance_scale=1, | |
| alt_scale=0, | |
| audio_guidance_scale=1, | |
| audio_scale=1, | |
| embedded_guidance_scale=1, | |
| repeat_generation=1, | |
| multi_prompts_gen_type="PG", | |
| multi_images_gen_type="0", | |
| skip_steps_cache_type="", | |
| skip_steps_multiplier="1.75", | |
| skip_steps_start_step_perc=0, | |
| self_refiner_setting="0", | |
| self_refiner_f_uncertainty=0, | |
| self_refiner_certain_percentage=0.999, | |
| output_filename="", | |
| mode="", | |
| video_source=DEFAULT_VIDEO, | |
| video_guide=DEFAULT_VIDEO, | |
| video_mask=DEFAULT_VIDEO, | |
| keep_frames_video_guide="", | |
| keep_frames_video_source="", | |
| input_video_strength=1, | |
| audio_guide=DEFAULT_AUDIO, | |
| audio_guide2=DEFAULT_AUDIO, | |
| audio_source=DEFAULT_AUDIO, | |
| replace_voice_sample=DEFAULT_AUDIO, | |
| replace_voice_sample2=DEFAULT_AUDIO, | |
| custom_guide=DEFAULT_FILE, | |
| replace_voice_method="", | |
| postprocess_audio="", | |
| postprocess_audio_prompt="", | |
| postprocess_audio_neg_prompt="", | |
| speakers_locations="0:45 55:100", | |
| sliding_window_size=81, | |
| sliding_window_overlap=5, | |
| sub_parallel_window_size=0, | |
| sub_parallel_window_overlap=17, | |
| sliding_window_color_correction_strength=0, | |
| sliding_window_overlap_noise=0, | |
| sliding_window_discard_last_frames=0, | |
| sliding_window_trim_first_frames=0, | |
| NAG_scale=1, | |
| NAG_tau=3.5, | |
| NAG_alpha=0.5, | |
| perturbation_switch="0", | |
| perturbation_layers=[9], | |
| perturbation_start_perc=10, | |
| perturbation_end_perc=90, | |
| apg_switch="0", | |
| cfg_star_switch="0", | |
| cfg_zero_step=-1, | |
| min_frames_if_references="1", | |
| RIFLEx_setting="0", | |
| force_fps="", | |
| api_name="/save_inputs_1", | |
| ) | |
| images = _extract_images(result) | |
| saved = [] | |
| for i, img_info in enumerate(images): | |
| try: | |
| path = OUTPUT_DIR / f"{task_id}_{i}.png" | |
| _download_image(img_info, path) | |
| saved.append( | |
| { | |
| "index": i, | |
| "url": f"/api/flux2/file/{task_id}_{i}.png", | |
| "width": img_info.get("image", {}).get("width"), | |
| "height": img_info.get("image", {}).get("height"), | |
| } | |
| if isinstance(img_info, dict) | |
| else {"index": i, "url": f"/api/flux2/file/{task_id}_{i}.png"} | |
| ) | |
| except Exception as e: | |
| saved.append({"index": i, "error": str(e)}) | |
| with _tasks_lock: | |
| _tasks[task_id] = {"status": "done", "images": saved} | |
| tracking.emit("job_done", ctx, latency_ms=int((time.time() - started) * 1000), | |
| job_id=task_id, kind="flux2", phase="generate", items=len(saved)) | |
| except Exception as e: | |
| import traceback | |
| with _tasks_lock: | |
| _tasks[task_id] = { | |
| "status": "error", | |
| "error": str(e), | |
| "traceback": traceback.format_exc(), | |
| } | |
| tracking.emit("job_failed", ctx, latency_ms=int((time.time() - started) * 1000), | |
| job_id=task_id, kind="flux2", phase="generate", error=str(e)[:200]) | |
| async def api_health(): | |
| try: | |
| c = _get_client() | |
| endpoints = c.view_api(all_endpoints=True, return_format="dict") if hasattr(c, "view_api") else {} | |
| return {"connected": True, "url": WANGP_URL} | |
| except Exception as e: | |
| return {"connected": False, "url": WANGP_URL, "error": str(e)} | |
| async def api_generate(req: GenRequest): | |
| task_id = str(uuid.uuid4()) | |
| with _tasks_lock: | |
| _tasks[task_id] = {"status": "queued"} | |
| # Bắt ngữ cảnh theo dõi NGAY tại request: hàm chạy ở luồng nền, ContextVar | |
| # của request không còn sống tới đó. | |
| ctx = get_ctx() | |
| tracking.emit("job_queued", ctx, job_id=task_id, kind="flux2") | |
| submit_bg(_generate, task_id, req.model_dump(), ctx) | |
| return {"task_id": task_id, "status": "queued"} | |
| async def api_status(task_id: str): | |
| with _tasks_lock: | |
| task = _tasks.get(task_id) | |
| if not task: | |
| raise HTTPException(404, "Task not found") | |
| return task | |
| async def api_file(filename: str): | |
| path = OUTPUT_DIR / filename | |
| if not path.exists(): | |
| raise HTTPException(404, "File not found") | |
| return FileResponse(str(path), media_type="image/png") | |