"""Forward a visitor's ZeroGPU identity to the protected HeadSwap app.""" import asyncio import logging import tempfile import time import uuid import ui_stats import gradio as gr from gradio_client import Client, handle_file from gradio_client.exceptions import AppError from gradio_client.utils import StatusUpdate from PIL import Image BACKEND_URL = 'https://keysersoze-8m-headswap.hf.space/' PUBLIC_URL = 'https://huggingface.co/spaces/keysersoze/Faceswap-Headswap' LOGGER = logging.getLogger('headswap.frontend') async def result_with_gpu_notices(job): """Consume every live event so short-lived GPU notices are not lost to polling.""" async for update in job: if not isinstance(update, StatusUpdate) or not update.log: continue message, level = update.log # These are the user-facing scheduler notices emitted by spaces 0.51.3. # Do not infer GPU acquisition from Gradio's PROCESSING status. if level == 'info' and message in ( 'Waiting for a GPU to become available', 'Waiting for a GPU slot on this Space', ): gr.Info(message) elif level == 'success' and message == 'Successfully acquired a GPU': gr.Success(message) return job.result() # retain the client's final output and structured errors def visitor_headers(request): """Only forward HF's signed quota identity; never substitute an owner token.""" headers = getattr(request, 'headers', None) or {} identity = headers.get('x-ip-token') if not identity: raise gr.Error( 'Your Hugging Face GPU identity did not reach the app. ' f'Open HeadSwap on Hugging Face, ' 'sign in, and try again.', title='Hugging Face sign-in needed', print_exception=False, ) return {'x-ip-token': identity} def swap(target, head, seed, randomize_seed, request: gr.Request): if target is None or head is None: ui_stats.count('input_error') raise gr.Error('Please upload both the photo to change and the new head.', title='Images required', print_exception=False) if not randomize_seed: try: valid_seed = int(seed) if valid_seed != seed or not 0 <= valid_seed <= 2**64 - 1: raise ValueError except (TypeError, ValueError, OverflowError): ui_stats.count('input_error') raise gr.Error('Please enter a whole-number seed from 0 to 18446744073709551615.', title='Invalid seed', print_exception=False) from None seed = valid_seed headers = visitor_headers(request) request_id = uuid.uuid4().hex[:12] started = time.monotonic() LOGGER.info('Generation started [request_id=%s identity_forwarded=true]', request_id) client = None try: with tempfile.TemporaryDirectory(prefix='headswap-') as downloads: # A fresh client isolates headers, session and downloaded files per call. # The protected app URL is public: token=False disables implicit owner auth. client = Client(BACKEND_URL, token=False, headers=headers, verbose=False, download_files=downloads, analytics_enabled=False) job = client.submit(handle_file(target), handle_file(head), seed, randomize_seed, api_name='/swap') # This synchronous Gradio callback runs in a worker thread; asyncio.run # preserves its contextvars, keeping toasts scoped to this visitor. pair, seed_used = asyncio.run(result_with_gpu_notices(job)) images = [] for path in pair: with Image.open(path) as image: images.append(image.convert('RGB')) LOGGER.info('Generation completed [request_id=%s elapsed_seconds=%.2f]', request_id, time.monotonic() - started) return tuple(images), seed_used except AppError as error: LOGGER.warning('Generation refused [request_id=%s title=%s]: %s', request_id, error.title, error.message) # Preserve run limits, time quotas, retry links and all other backend errors. raise gr.Error(error.message, title=error.title, duration=error.duration, visible=error.visible, print_exception=False) from None except Exception as error: # Transport exception strings can contain request URLs/headers. Log only type. LOGGER.error('Backend request failed [request_id=%s error_type=%s]', request_id, type(error).__name__) raise gr.Error('The generation service could not complete this request. ' f'Please try again. Error ID: {request_id}.', title='Generation service unavailable', print_exception=False) from None finally: if client is not None: client.close()