kenfoo commited on
Commit
12fcbf3
·
verified ·
1 Parent(s): 672f2a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -47
app.py CHANGED
@@ -1,14 +1,14 @@
1
  import gradio as gr
2
- from gradio_client import Client, handle_file
3
  import random
4
  import os
 
5
 
6
  HF_TOKEN = os.environ.get("girlToken")
7
 
8
- space_client = Client(
9
- "prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast",
10
- token=HF_TOKEN #不是hf_token
11
- )
12
 
13
  LORA_STYLES = [
14
  'Multiple-Angles', 'Photo-to-Anime', 'Anime-V2', 'Light-Migration',
@@ -20,6 +20,40 @@ LORA_STYLES = [
20
  ]
21
  MAX_SEED = 2**31 - 1
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  def infer(
25
  image,
@@ -42,59 +76,65 @@ def infer(
42
  if randomize_seed:
43
  seed = random.randint(0, MAX_SEED)
44
 
45
- # 关键:用 handle_file 上传到目标 Space,得到远端可访问的文件对象
46
- uploaded = handle_file(image)
47
-
48
- # 补全所有必要字段
49
- # uploaded["url"] = None
50
- # uploaded["size"] = os.path.getsize(image)
51
- # uploaded["mime_type"] = "image/jpeg"
52
- # uploaded["is_stream"] = False
53
-
54
- #images_input = [{"image": uploaded, "caption": None}]
55
-
56
- # Gallery 元素格式:{"image": <上传后的文件对象>, "caption": None}
57
- images_input = [{"image": uploaded, "caption": None}]
58
-
59
- print("[调用API] 输入参数:")
60
- print(f" image path: {image}")
61
- print(f" uploaded: {uploaded}")
62
- print(f" prompt: {prompt}")
63
- print(f" lora_adapter: {lora_adapter}")
64
- print(f" seed: {seed}")
65
- print(f" guidance_scale: {guidance_scale}")
66
- print(f" steps: {steps}")
67
-
68
  try:
69
- result = space_client.predict(
70
- images=images_input,
71
- prompt=prompt,
72
- lora_adapter=lora_adapter,
73
- seed=int(seed),
74
- randomize_seed=bool(randomize_seed),
75
- guidance_scale=int(guidance_scale),
76
- steps=int(steps),
77
- api_name="/infer",
78
- )
79
-
80
- print(f"[调用API] 返回值: {result}")
81
-
82
- image_info, seed_used = result
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  if isinstance(image_info, dict):
85
  img_out = image_info.get("path") or image_info.get("url")
86
  else:
87
  img_out = image_info
88
-
 
 
89
  return img_out, int(seed_used)
90
-
91
  except Exception as e:
92
  import traceback
93
  traceback.print_exc()
94
- print(f"[调用API] 异常: {e}")
95
  return None, seed
96
 
97
-
98
  css = """
99
  #col-container {
100
  margin: 0 auto;
@@ -104,7 +144,7 @@ css = """
104
 
105
  with gr.Blocks(css=css) as demo:
106
  with gr.Column(elem_id="col-container"):
107
- gr.Markdown("# 图像编辑 Demo\n基于 prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast")
108
 
109
  image = gr.Image(
110
  label="上传图片",
 
1
  import gradio as gr
 
2
  import random
3
  import os
4
+ import requests
5
 
6
  HF_TOKEN = os.environ.get("girlToken")
7
 
8
+ API_BASE = "https://prithivmlmods-qwen-image-edit-2511-loras-fast.hf.space"
9
+ UPLOAD_URL = f"{API_BASE}/gradio_api/upload"
10
+ CALL_URL = f"{API_BASE}/gradio_api/call/v2/infer"
11
+ POLL_URL = f"{API_BASE}/gradio_api/call/infer" # need event_id
12
 
13
  LORA_STYLES = [
14
  'Multiple-Angles', 'Photo-to-Anime', 'Anime-V2', 'Light-Migration',
 
20
  ]
21
  MAX_SEED = 2**31 - 1
22
 
23
+ def upload_file(image_path):
24
+ files = {'files': (os.path.basename(image_path), open(image_path, "rb"), "application/octet-stream")}
25
+ headers = {'Authorization': f'Bearer {HF_TOKEN}'}
26
+ resp = requests.post(UPLOAD_URL, files=files, headers=headers)
27
+ resp.raise_for_status()
28
+ res = resp.json()
29
+ # 返回格式可能是list或dict
30
+ if isinstance(res, list) and len(res) > 0:
31
+ return res[0]
32
+ return res
33
+
34
+ def call_infer(payload):
35
+ headers = {'Authorization': f'Bearer {HF_TOKEN}'}
36
+ resp = requests.post(CALL_URL, json=payload, headers=headers)
37
+ resp.raise_for_status()
38
+ job = resp.json()
39
+ event_id = job.get("event_id")
40
+ return event_id
41
+
42
+ def poll_infer(event_id):
43
+ url = f"{POLL_URL}/{event_id}"
44
+ headers = {'Authorization': f'Bearer {HF_TOKEN}'}
45
+ # 简单轮询直到拿到结果(可优化为更好策略)
46
+ import time
47
+ for _ in range(60):
48
+ resp = requests.get(url, headers=headers)
49
+ resp.raise_for_status()
50
+ result = resp.json()
51
+ if result.get("status") == "complete":
52
+ return result.get("data"), result.get("outputs")
53
+ elif result.get("status") == "error":
54
+ raise Exception(result.get("error"))
55
+ time.sleep(2) # 2秒再次轮询
56
+ raise TimeoutError("等候API返回超时")
57
 
58
  def infer(
59
  image,
 
76
  if randomize_seed:
77
  seed = random.randint(0, MAX_SEED)
78
 
79
+ # 1. 上传文件
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  try:
81
+ uploaded_info = upload_file(image)
82
+ # 提交给API需要包装成和官方一样的dict
83
+ img_obj = {
84
+ "path": uploaded_info["path"],
85
+ "meta": {"_type": "gradio.FileData"},
86
+ "orig_name": os.path.basename(image)
87
+ }
88
+ except Exception as e:
89
+ print(f"[图片上传] 失败: {e}")
90
+ return None, seed
 
 
 
 
91
 
92
+ # 2. 准备参数并调用推理
93
+ payload = {
94
+ "images": [{"image": img_obj, "caption": None}],
95
+ "prompt": prompt,
96
+ "lora_adapter": lora_adapter,
97
+ "seed": int(seed),
98
+ "randomize_seed": bool(randomize_seed),
99
+ "guidance_scale": float(guidance_scale),
100
+ "steps": int(steps),
101
+ }
102
+
103
+ print("准备调用远端API:", payload)
104
+ try:
105
+ event_id = call_infer(payload)
106
+ print("API返回event_id: ", event_id)
107
+ # 3. 结果轮询
108
+ data, outputs = poll_infer(event_id)
109
+ print("[API 完成] data:", data, "outputs:", outputs)
110
+ # 解析输出(通常outputs可能就是结果图片的路径)
111
+ # 兼容dict或list
112
+ image_info = None
113
+ seed_used = seed
114
+ if outputs:
115
+ if isinstance(outputs, list) and len(outputs) == 2:
116
+ image_info, seed_used = outputs
117
+ elif isinstance(outputs, dict):
118
+ image_info = outputs.get("path") or outputs.get("url")
119
+ seed_used = outputs.get("seed", seed)
120
+ else:
121
+ image_info = outputs
122
+ elif data:
123
+ image_info = data
124
  if isinstance(image_info, dict):
125
  img_out = image_info.get("path") or image_info.get("url")
126
  else:
127
  img_out = image_info
128
+ # 补成绝对地址
129
+ if img_out and not img_out.startswith("http"):
130
+ img_out = API_BASE + img_out
131
  return img_out, int(seed_used)
 
132
  except Exception as e:
133
  import traceback
134
  traceback.print_exc()
135
+ print(f"[API 调用异常] {e}")
136
  return None, seed
137
 
 
138
  css = """
139
  #col-container {
140
  margin: 0 auto;
 
144
 
145
  with gr.Blocks(css=css) as demo:
146
  with gr.Column(elem_id="col-container"):
147
+ gr.Markdown("# 图像编辑 Demo\n基于 prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast (新版API)")
148
 
149
  image = gr.Image(
150
  label="上传图片",