import requests import os import gradio as gr from gradio_client import Client, handle_file import random HF_TOKEN = os.environ.get("girlToken") TARGET_SPACE_URL = "https://prithivmlmods-qwen-image-edit-2511-loras-fast.hf.space" def upload_file_to_space(local_path): """手动上传文件到目标 Space,返回远端 URL""" upload_url = f"{TARGET_SPACE_URL}/upload" headers = {} if HF_TOKEN: headers["Authorization"] = f"Bearer {HF_TOKEN}" with open(local_path, "rb") as f: response = requests.post( upload_url, headers=headers, files={"files": (os.path.basename(local_path), f, "image/jpeg")}, ) print(f"上传状态码: {response.status_code}") print(f"上传响应: {response.text}") if response.status_code == 200: result = response.json() # 返回的是文件路径列表,取第一个 remote_path = result[0] if isinstance(result, list) else result return remote_path else: raise Exception(f"上传失败: {response.status_code} {response.text}") def infer(image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress(track_tqdm=True)): if image is None or not os.path.exists(image): return None, seed if randomize_seed: seed = random.randint(0, MAX_SEED) # 手动上传,拿到远端路径 remote_path = upload_file_to_space(image) print(f"远端路径: {remote_path}") # 用远端路径构造 images 参数 images_input = [{ "image": { "path": remote_path, "url": f"{TARGET_SPACE_URL}/file={remote_path}", "size": os.path.getsize(image), "orig_name": os.path.basename(image), "mime_type": "image/jpeg", "is_stream": False, "meta": {} }, "caption": None }] print(f"images_input: {images_input}") try: result = space_client.predict( images=images_input, prompt=prompt, lora_adapter=lora_adapter, seed=float(seed), randomize_seed=bool(randomize_seed), guidance_scale=float(guidance_scale), steps=float(steps), api_name="/infer", ) image_info, seed_used = result img_out = image_info.get("path") or image_info.get("url") return img_out, int(seed_used) except Exception as e: import traceback traceback.print_exc() print(f"[调用API] 异常: {e}") return None, seed