import os import sys # Add model/ to Python path so imports like 'from src.xxx', 'import apply_net', # 'from detectron2.xxx', etc. continue to resolve without changing any import statements. sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'model')) import threading import json from datetime import datetime, timezone os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0" os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] = "120" try: import spaces except ImportError: class MockSpaces: @staticmethod def GPU(fn=None, duration=None): if fn is not None: return fn def decorator(f): return f return decorator import sys sys.modules['spaces'] = MockSpaces import spaces # Monkey-patch gradio_client to prevent Pydantic schema compatibility crash (TypeError: argument of type 'bool' is not iterable) try: import gradio_client.utils _orig_json_schema_to_python_type = gradio_client.utils._json_schema_to_python_type def _patched_json_schema_to_python_type(schema, defs): if isinstance(schema, bool): return "Any" return _orig_json_schema_to_python_type(schema, defs) gradio_client.utils._json_schema_to_python_type = _patched_json_schema_to_python_type _orig_get_type = gradio_client.utils.get_type def _patched_get_type(schema): if not isinstance(schema, dict): return {} return _orig_get_type(schema) gradio_client.utils.get_type = _patched_get_type except Exception as e: print(f"Failed to patch gradio_client: {e}") import gradio as gr from PIL import Image import os import uuid import time import base64 from io import BytesIO from huggingface_hub import HfApi from fastapi import FastAPI, Request, BackgroundTasks, Form from fastapi.staticfiles import StaticFiles from pydantic import BaseModel from fastapi.responses import JSONResponse import uvicorn from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline from src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_ref from src.unet_hacked_tryon import UNet2DConditionModel from transformers import ( CLIPImageProcessor, CLIPVisionModelWithProjection, CLIPTextModel, CLIPTextModelWithProjection, ) from diffusers import DDPMScheduler,AutoencoderKL from typing import List import torch import os from transformers import AutoTokenizer import numpy as np from utils_mask import get_mask_location from torchvision import transforms import apply_net from preprocess.humanparsing.run_parsing import Parsing from preprocess.openpose.run_openpose import OpenPose from detectron2.data.detection_utils import convert_PIL_to_numpy,_apply_exif_orientation from torchvision.transforms.functional import to_pil_image def pil_to_binary_mask(pil_image, threshold=0): np_image = np.array(pil_image) grayscale_image = Image.fromarray(np_image).convert("L") binary_mask = np.array(grayscale_image) > threshold mask = np.zeros(binary_mask.shape, dtype=np.uint8) for i in range(binary_mask.shape[0]): for j in range(binary_mask.shape[1]): if binary_mask[i,j] == True : mask[i,j] = 1 mask = (mask*255).astype(np.uint8) output_mask = Image.fromarray(mask) return output_mask base_path = 'yisol/IDM-VTON' example_path = os.path.join(os.path.dirname(__file__), 'model', 'example') INSTAGRAM_MODULE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "instagram", "poster") _instagram_poster = None _instagram_poster_lock = threading.Lock() LATEST_OUTPUT_FILENAME = None def _get_instagram_poster(): global _instagram_poster with _instagram_poster_lock: if _instagram_poster is None: import importlib.util poster_path = os.path.join(INSTAGRAM_MODULE_DIR, "instagram_poster.py") spec = importlib.util.spec_from_file_location( "fashionai_instagram_poster", poster_path ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) _instagram_poster = module.InstagramPoster() return _instagram_poster def _instagram_caption(instagram_caption: str, garment_des: str) -> str: return (instagram_caption or garment_des or "").strip() def schedule_instagram_post(output_path: str, caption: str) -> None: """Upload to Instagram in a background thread (does not block the UI).""" def _run(): try: poster = _get_instagram_poster() result = poster.post_from_path(output_path, caption) print(f"[instagram] Posted: {result.get('post_url', result)}") except Exception as e: print(f"[instagram] Auto-post failed: {e}") threading.Thread(target=_run, daemon=True).start() # ── HF Dataset Storage ────────────────────────────────────────────────────── HF_DATASET_REPO = os.environ.get("HF_DATASET_REPO", "Lakshay3605/idm-vton-outputs") HF_TOKEN = os.environ.get("HF_TOKEN", "") def upload_to_hf_dataset(image, garment_des=""): """ Upload a PIL image to the HF dataset repo as PNG. Also writes latest_image.json with the public URL and metadata. Returns (public_url, error_message). error_message is empty on success. """ if not HF_TOKEN: return "", "HF_TOKEN not set — skipping dataset upload" try: api = HfApi(token=HF_TOKEN) # Auto-create the dataset repo if it doesn't exist try: api.create_repo( repo_id=HF_DATASET_REPO, repo_type="dataset", private=False, exist_ok=True ) except Exception as repo_err: print(f"[hf-dataset] Note on repo creation/check: {repo_err}") # Unique filename using timestamp + short UUID ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") uid = uuid.uuid4().hex[:8] filename = f"{ts}_{uid}.png" # Save image to bytes buffer as PNG buf = BytesIO() if image.mode in ("RGBA", "P"): image = image.convert("RGB") image.save(buf, format="PNG") buf.seek(0) # Upload image file to dataset repo api.upload_file( path_or_fileobj=buf, path_in_repo=filename, repo_id=HF_DATASET_REPO, repo_type="dataset", ) # Construct the public URL public_url = ( f"https://huggingface.co/datasets/{HF_DATASET_REPO}" f"/resolve/main/{filename}" ) # Write latest_image.json to the same repo iso_ts = datetime.now(timezone.utc).isoformat() latest_data = { "url": public_url, "timestamp": iso_ts, "filename": filename, "caption": garment_des or "", } json_buf = BytesIO(json.dumps(latest_data, indent=2).encode("utf-8")) api.upload_file( path_or_fileobj=json_buf, path_in_repo="latest_image.json", repo_id=HF_DATASET_REPO, repo_type="dataset", ) print(f"[hf-dataset] Uploaded {filename} → {public_url}") return public_url, "" except Exception as e: print(f"[hf-dataset] Upload failed: {e}") return "", f"Dataset upload failed: {e}" def post_latest_to_instagram(last_output_path, instagram_caption, garment_des): if not last_output_path or not os.path.isfile(last_output_path): return gr.update(value="Generate a try-on image first.", visible=True) caption = _instagram_caption(instagram_caption, garment_des) if not caption: return gr.update( value="Add an Instagram caption or garment description before posting.", visible=True, ) try: poster = _get_instagram_poster() result = poster.post_from_path(last_output_path, caption) return gr.update( value=f"Posted to Instagram: [{result['post_url']}]({result['post_url']})", visible=True, ) except ValueError as e: return gr.update( value=f"Instagram not configured. Copy `INSTAGRAM/INSTAGRAM/.env.example` to `.env` and set credentials. ({e})", visible=True, ) except Exception as e: return gr.update(value=f"Instagram post failed: {e}", visible=True) unet = UNet2DConditionModel.from_pretrained( base_path, subfolder="unet", torch_dtype=torch.float16, ) unet.requires_grad_(False) tokenizer_one = AutoTokenizer.from_pretrained( base_path, subfolder="tokenizer", revision=None, use_fast=False, ) tokenizer_two = AutoTokenizer.from_pretrained( base_path, subfolder="tokenizer_2", revision=None, use_fast=False, ) noise_scheduler = DDPMScheduler.from_pretrained(base_path, subfolder="scheduler") text_encoder_one = CLIPTextModel.from_pretrained( base_path, subfolder="text_encoder", torch_dtype=torch.float16, ) text_encoder_two = CLIPTextModelWithProjection.from_pretrained( base_path, subfolder="text_encoder_2", torch_dtype=torch.float16, ) image_encoder = CLIPVisionModelWithProjection.from_pretrained( base_path, subfolder="image_encoder", torch_dtype=torch.float16, ) vae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=torch.float16, ) # "stabilityai/stable-diffusion-xl-base-1.0", UNet_Encoder = UNet2DConditionModel_ref.from_pretrained( base_path, subfolder="unet_encoder", torch_dtype=torch.float16, use_safetensors=True, ) parsing_model = Parsing(0) openpose_model = OpenPose(0) UNet_Encoder.requires_grad_(False) image_encoder.requires_grad_(False) vae.requires_grad_(False) unet.requires_grad_(False) text_encoder_one.requires_grad_(False) text_encoder_two.requires_grad_(False) tensor_transfrom = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) pipe = TryonPipeline.from_pretrained( base_path, unet=unet, vae=vae, feature_extractor= CLIPImageProcessor(), text_encoder = text_encoder_one, text_encoder_2 = text_encoder_two, tokenizer = tokenizer_one, tokenizer_2 = tokenizer_two, scheduler = noise_scheduler, image_encoder=image_encoder, torch_dtype=torch.float16, ) pipe.unet_encoder = UNet_Encoder @spaces.GPU def start_tryon(input_dict,garm_img,garment_des,is_checked,is_checked_crop,denoise_steps,seed): device = "cuda" openpose_model.preprocessor.body_estimation.model.to(device) pipe.to(device) pipe.unet_encoder.to(device) garm_img= garm_img.convert("RGB").resize((768,1024)) human_img_orig = input_dict["background"].convert("RGB") if is_checked_crop: width, height = human_img_orig.size target_width = int(min(width, height * (3 / 4))) target_height = int(min(height, width * (4 / 3))) left = (width - target_width) / 2 top = (height - target_height) / 2 right = (width + target_width) / 2 bottom = (height + target_height) / 2 cropped_img = human_img_orig.crop((left, top, right, bottom)) crop_size = cropped_img.size human_img = cropped_img.resize((768,1024)) else: human_img = human_img_orig.resize((768,1024)) if is_checked: keypoints = openpose_model(human_img.resize((384,512))) model_parse, _ = parsing_model(human_img.resize((384,512))) mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints) mask = mask.resize((768,1024)) else: mask = pil_to_binary_mask(input_dict['layers'][0].convert("RGB").resize((768, 1024))) # mask = transforms.ToTensor()(mask) # mask = mask.unsqueeze(0) mask_gray = (1-transforms.ToTensor()(mask)) * tensor_transfrom(human_img) mask_gray = to_pil_image((mask_gray+1.0)/2.0) human_img_arg = _apply_exif_orientation(human_img.resize((384,512))) human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR") args = apply_net.create_argument_parser().parse_args(('show', './model/configs/densepose_rcnn_R_50_FPN_s1x.yaml', './model/ckpt/densepose/model_final_162be9.pkl', 'dp_segm', '-v', '--opts', 'MODEL.DEVICE', 'cuda')) # verbosity = getattr(args, "verbosity", None) pose_img = args.func(args,human_img_arg) pose_img = pose_img[:,:,::-1] pose_img = Image.fromarray(pose_img).resize((768,1024)) with torch.no_grad(): # Extract the images with torch.cuda.amp.autocast(): with torch.no_grad(): prompt = "model is wearing " + garment_des negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality" with torch.inference_mode(): ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = pipe.encode_prompt( prompt, num_images_per_prompt=1, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt = "a photo of " + garment_des negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality" if not isinstance(prompt, List): prompt = [prompt] * 1 if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * 1 with torch.inference_mode(): ( prompt_embeds_c, _, _, _, ) = pipe.encode_prompt( prompt, num_images_per_prompt=1, do_classifier_free_guidance=False, negative_prompt=negative_prompt, ) pose_img = tensor_transfrom(pose_img).unsqueeze(0).to(device,torch.float16) garm_tensor = tensor_transfrom(garm_img).unsqueeze(0).to(device,torch.float16) generator = torch.Generator(device).manual_seed(seed) if seed is not None else None images = pipe( prompt_embeds=prompt_embeds.to(device,torch.float16), negative_prompt_embeds=negative_prompt_embeds.to(device,torch.float16), pooled_prompt_embeds=pooled_prompt_embeds.to(device,torch.float16), negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device,torch.float16), num_inference_steps=denoise_steps, generator=generator, strength = 1.0, pose_img = pose_img.to(device,torch.float16), text_embeds_cloth=prompt_embeds_c.to(device,torch.float16), cloth = garm_tensor.to(device,torch.float16), mask_image=mask, image=human_img, height=1024, width=768, ip_adapter_image = garm_img.resize((768,1024)), guidance_scale=2.0, )[0] if is_checked_crop: out_img = images[0].resize(crop_size) human_img_orig.paste(out_img, (int(left), int(top))) return human_img_orig, mask_gray else: return images[0], mask_gray def start_tryon_wrapper( input_dict, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed, auto_post_instagram=False, instagram_caption="", request: gr.Request = None, view_name="front", filename_holder=None, ): global LATEST_OUTPUT_FILENAME # Call the GPU function result_img, mask_img = start_tryon(input_dict, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed) # Save the output images to static directory (on the CPU web server/host) os.makedirs("./static/outputs", exist_ok=True) unique_id = f"{uuid.uuid4().hex[:8]}_{int(time.time())}" output_filename = f"{view_name}_{unique_id}.jpg" mask_filename = f"{view_name}_{unique_id}_mask.jpg" output_path = os.path.join("./static/outputs", output_filename) mask_path = os.path.join("./static/outputs", mask_filename) result_img.save(output_path, "JPEG") mask_img.save(mask_path, "JPEG") LATEST_OUTPUT_FILENAME = output_filename if isinstance(filename_holder, dict): filename_holder["output_filename"] = output_filename filename_holder["mask_filename"] = mask_filename filename_holder["output_path"] = output_path return result_img, mask_img # ── Upload to HF Dataset for permanent public storage ── public_url = "" url_display = "" public_url, upload_err = upload_to_hf_dataset(result_img, garment_des) if public_url: url_display = public_url elif upload_err: url_display = f"⚠️ {upload_err}" instagram_status = gr.update(value="", visible=False) if auto_post_instagram: caption = _instagram_caption(instagram_caption, garment_des) if caption: schedule_instagram_post(output_path, caption) instagram_status = gr.update( value="Posting latest try-on to Instagram in the background…", visible=True, ) else: instagram_status = gr.update( value="Auto-post skipped: add an Instagram caption or garment description.", visible=True, ) return result_img, mask_img, instagram_status, output_path, url_display garm_list = os.listdir(os.path.join(example_path,"cloth")) garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list] human_list = os.listdir(os.path.join(example_path,"human")) human_list_path = [os.path.join(example_path,"human",human) for human in human_list] human_ex_list = [] for ex_human in human_list_path: ex_dict= {} ex_dict['background'] = ex_human ex_dict['layers'] = None ex_dict['composite'] = None human_ex_list.append(ex_dict) ##default human image_blocks = gr.Blocks().queue() with image_blocks as demo: last_output_path_state = gr.State(value=None) gr.Markdown("## IDM-VTON 👕👔👚") gr.Markdown("Virtual Try-on with your image and garment image. Check out the [source codes](https://github.com/yisol/IDM-VTON) and the [model](https://huggingface.co/yisol/IDM-VTON)") with gr.Row(): with gr.Column(): imgs = gr.ImageEditor(sources=['upload'], type="pil", label='Human. Mask with pen or use auto-masking', interactive=True) with gr.Row(): is_checked = gr.Checkbox(label="Yes", info="Use auto-generated mask (Takes 5 seconds)",value=True) with gr.Row(): is_checked_crop = gr.Checkbox(label="Yes", info="Use auto-crop & resizing",value=False) example = gr.Examples( inputs=imgs, examples_per_page=10, examples=human_ex_list ) with gr.Column(): garm_img = gr.Image(label="Garment", sources=['upload'], type="pil") with gr.Row(elem_id="prompt-container"): with gr.Row(): prompt = gr.Textbox(placeholder="Description of garment ex) Short Sleeve Round Neck T-shirts", show_label=False, elem_id="prompt") example = gr.Examples( inputs=garm_img, examples_per_page=8, examples=garm_list_path) with gr.Column(): # image_out = gr.Image(label="Output", elem_id="output-img", height=400) masked_img = gr.Image(label="Masked image output", elem_id="masked-img",show_share_button=False) with gr.Column(): # image_out = gr.Image(label="Output", elem_id="output-img", height=400) image_out = gr.Image(label="Output", elem_id="output-img",show_share_button=False) public_url_box = gr.Textbox( label="Public Image URL", placeholder="URL will appear here after generation…", interactive=False, show_copy_button=True, elem_id="public-url", ) with gr.Column(): try_button = gr.Button(value="Try-on") with gr.Accordion(label="Advanced Settings", open=False): with gr.Row(): denoise_steps = gr.Number(label="Denoising Steps", minimum=20, maximum=40, value=30, step=1) seed = gr.Number(label="Seed", minimum=-1, maximum=2147483647, step=1, value=42) show_instagram = os.path.exists(os.path.join(INSTAGRAM_MODULE_DIR, "instagram_poster.py")) with gr.Accordion(label="Instagram", open=False, visible=show_instagram): gr.Markdown( "Posts the latest try-on output via `instagram/poster` (instagrapi). " "Set credentials in `instagram/poster/.env` and run `python cli.py --login` once." ) instagram_caption = gr.Textbox( label="Instagram caption (optional)", placeholder="Uses garment description if empty", ) auto_post_instagram = gr.Checkbox( label="Auto-post after each try-on", value=False, ) post_instagram_btn = gr.Button(value="Post latest output to Instagram") instagram_status = gr.Markdown(value="", visible=False) try_button.click( fn=start_tryon_wrapper, inputs=[ imgs, garm_img, prompt, is_checked, is_checked_crop, denoise_steps, seed, auto_post_instagram, instagram_caption, ], outputs=[image_out, masked_img, instagram_status, last_output_path_state, public_url_box], api_name="tryon", ) post_instagram_btn.click( fn=post_latest_to_instagram, inputs=[last_output_path_state, instagram_caption, prompt], outputs=instagram_status, ) # Create static directory os.makedirs("./static/outputs", exist_ok=True) # Helper task to clean up old files (>1 hour old) to prevent disk fill-up def cleanup_old_files(): now = time.time() outputs_dir = "./static/outputs" if os.path.exists(outputs_dir): for filename in os.listdir(outputs_dir): file_path = os.path.join(outputs_dir, filename) if os.path.isfile(file_path): if os.stat(file_path).st_mtime < now - 3600: try: os.remove(file_path) except Exception as e: print(f"Error removing {file_path}: {e}") # Launch the Gradio app directly on port 7860 (required by Hugging Face ZeroGPU runtime check) image_blocks.launch( server_name="0.0.0.0", server_port=7860, prevent_thread_lock=True ) # ── Autonomous Pipeline ───────────────────────────────────────────────────── # Start the autonomous orchestrator AFTER Gradio launches so the /call/tryon # API endpoint is available for the Gradio API fallback strategy. try: from orchestrator import AutoPipeline _auto_pipeline = AutoPipeline( tryon_fn=start_tryon, schedule=["10:00", "14:00", "18:00"], timezone="Asia/Kolkata", images_per_post=4, ) _auto_pipeline.start() print("[orchestrator] Autonomous pipeline started successfully.") except Exception as _orch_err: _auto_pipeline = None print(f"[orchestrator] Failed to start autonomous pipeline: {_orch_err}") import traceback traceback.print_exc() # Now that the Gradio app is launched, customize its internal FastAPI instance! app = image_blocks.app # Mount the static files directory app.mount("/static", StaticFiles(directory="static"), name="static") @app.get("/api/latest-image") async def api_latest_image(request: Request): global LATEST_OUTPUT_FILENAME outputs_dir = "./static/outputs" if not LATEST_OUTPUT_FILENAME: # Fallback: scan static/outputs/ directory for the newest file if os.path.exists(outputs_dir): files = [f for f in os.listdir(outputs_dir) if f.endswith(".jpg") and not f.endswith("_mask.jpg")] if files: files.sort(key=lambda x: os.path.getmtime(os.path.join(outputs_dir, x)), reverse=True) LATEST_OUTPUT_FILENAME = files[0] if not LATEST_OUTPUT_FILENAME: return JSONResponse({"status": "error", "message": "No images generated yet"}, status_code=404) file_path = os.path.join(outputs_dir, LATEST_OUTPUT_FILENAME) if not os.path.isfile(file_path): return JSONResponse({"status": "error", "message": f"Image file not found (Space may have restarted): {LATEST_OUTPUT_FILENAME}"}, status_code=404) # Return the image as base64 so the caller never depends on an ephemeral URL with open(file_path, "rb") as f: image_b64 = base64.b64encode(f.read()).decode("utf-8") return JSONResponse({ "status": "success", "output_filename": LATEST_OUTPUT_FILENAME, "image_data": f"data:image/jpeg;base64,{image_b64}" }) class TryonRequest(BaseModel): human_image: str garment_image: str garment_description: str view: str = "front" is_checked: bool = True is_checked_crop: bool = False denoise_steps: int = 30 seed: int = 42 post_to_instagram: bool = False instagram_caption: str = "" # Expose REST API endpoint on the Gradio-created FastAPI server # NOTE: This is at /api/rest-tryon (NOT /api/tryon) to avoid conflicting with # Gradio's auto-generated /api/tryon endpoint from api_name="tryon". # Clients should prefer the Gradio /call/tryon SSE protocol for ZeroGPU compat. @app.post("/api/rest-tryon") async def api_tryon( request: Request, background_tasks: BackgroundTasks, data: TryonRequest, ): # Queue cleanup task in background background_tasks.add_task(cleanup_old_files) try: human_image = data.human_image garment_image = data.garment_image garment_description = data.garment_description view = data.view is_checked = data.is_checked is_checked_crop = data.is_checked_crop denoise_steps = data.denoise_steps seed = data.seed post_to_instagram = data.post_to_instagram instagram_caption = data.instagram_caption # Decode base64 human image if "," in human_image: human_image = human_image.split(",")[1] human_pil = Image.open(BytesIO(base64.b64decode(human_image))).convert("RGB") # Decode base64 garment image if "," in garment_image: garment_image = garment_image.split(",")[1] garm_pil = Image.open(BytesIO(base64.b64decode(garment_image))).convert("RGB") # Create input dictionary for start_tryon format input_dict = { "background": human_pil, "layers": [None], "composite": None } # Call try_on with filename holder to capture output filenames filename_holder = {} start_tryon_wrapper( input_dict, garm_pil, garment_description, is_checked, is_checked_crop, denoise_steps, seed, view_name=view, filename_holder=filename_holder ) # Get base URL of the request dynamically, respecting HF reverse proxy headers proto = request.headers.get("x-forwarded-proto", "http") host = request.headers.get("x-forwarded-host", request.headers.get("host", "localhost:7860")) base_url = f"{proto}://{host}" output_filename = filename_holder.get("output_filename") mask_filename = filename_holder.get("mask_filename") output_path = filename_holder.get("output_path") response = { "status": "success", "view": view, "image_url": f"{base_url}/static/outputs/{output_filename}", "mask_url": f"{base_url}/static/outputs/{mask_filename}", "output_filename": output_filename, "mask_filename": mask_filename, } if post_to_instagram: caption = _instagram_caption(instagram_caption, garment_description) if not caption: response["instagram"] = { "status": "skipped", "message": "Caption required (instagram_caption or garment_description)", } elif not output_path: response["instagram"] = {"status": "error", "message": "Output path missing"} else: try: poster = _get_instagram_poster() ig_result = poster.post_from_path(output_path, caption) response["instagram"] = { "status": "posted", "post_url": ig_result["post_url"], "media_id": ig_result["media_id"], } except Exception as e: response["instagram"] = {"status": "error", "message": str(e)} return JSONResponse(response) except Exception as e: import traceback traceback.print_exc() return JSONResponse({"status": "error", "message": str(e)}, status_code=500) @app.get("/api/orchestrator-status") async def api_orchestrator_status(): """Return the current status of the autonomous posting pipeline.""" if _auto_pipeline is None: return JSONResponse( {"status": "error", "message": "Orchestrator not initialised"}, status_code=503, ) return JSONResponse({"status": "ok", **_auto_pipeline.get_status()}) # Keep the main process running while True: time.sleep(1)