kenfoo commited on
Commit
80d18f3
·
verified ·
1 Parent(s): bc0e444

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -20
app.py CHANGED
@@ -9,7 +9,7 @@ from io import BytesIO
9
  HF_TOKEN = os.environ.get("girlToken")
10
 
11
  API_BASE = "https://prithivmlmods-qwen-image-edit-2511-loras-fast.hf.space"
12
- INFER_URL = f"{API_BASE}/gradio/infer" # Not used, for clarity
13
  NAMED_API_URL = f"{API_BASE}/gradio_api/call/v2/infer"
14
 
15
  LORA_STYLES = [
@@ -22,11 +22,14 @@ LORA_STYLES = [
22
  ]
23
  MAX_SEED = 2**31 - 1
24
 
25
- def encode_image_file_to_b64_json(image_path):
 
 
 
26
  try:
27
  with open(image_path, "rb") as f:
28
  image_bytes = f.read()
29
- # 检查格式,果不是 jpeg/png 尝试转码
30
  try:
31
  img = Image.open(BytesIO(image_bytes))
32
  buffered = BytesIO()
@@ -35,7 +38,6 @@ def encode_image_file_to_b64_json(image_path):
35
  except Exception:
36
  pass
37
  im_b64 = base64.b64encode(image_bytes).decode("utf-8")
38
- # 和 gradio_client 一致,图片用 json 数组包裹并带类型
39
  payload = [
40
  {
41
  "data": im_b64,
@@ -43,13 +45,12 @@ def encode_image_file_to_b64_json(image_path):
43
  "orig_name": os.path.basename(image_path),
44
  }
45
  ]
46
- import json
47
- return json.dumps(payload)
48
  except Exception as e:
49
  raise RuntimeError(f"图片编码失败: {e}")
50
 
51
  def call_named_infer(
52
- images_b64_json,
53
  prompt,
54
  lora_adapter,
55
  seed,
@@ -62,31 +63,35 @@ def call_named_infer(
62
  'Content-Type': 'application/json'
63
  }
64
  payload = {
65
- "images_b64_json": images_b64_json,
66
  "prompt": prompt,
67
  "lora_adapter": lora_adapter,
68
  "seed": int(seed),
69
  "randomize_seed": bool(randomize_seed),
70
- "guidance_scale": float(guidance_scale), # 注意类型
71
  "steps": int(steps),
72
  }
73
- print("准备调用/infer:", payload)
74
- resp = requests.post(NAMED_API_URL, json=payload, headers=headers)
 
 
75
  resp.raise_for_status()
76
- # gradio api新版返回 event_id,然后/POLL 获取最终结果
77
  job = resp.json()
78
  event_id = job.get("event_id")
79
  return event_id
80
 
81
  def poll_infer(event_id):
82
- # 必须用 gradio_api/call/infer/{event_id}
83
  url = f"{API_BASE}/gradio_api/call/infer/{event_id}"
84
  headers = {'Authorization': f'Bearer {HF_TOKEN}'}
85
  import time
86
- for _ in range(60):
87
  resp = requests.get(url, headers=headers)
88
- resp.raise_for_status()
89
- result = resp.json()
 
 
 
 
90
  if result.get("status") == "complete":
91
  return result.get("data"), result.get("outputs")
92
  elif result.get("status") == "error":
@@ -116,14 +121,14 @@ def infer(
116
  seed = random.randint(0, MAX_SEED)
117
 
118
  try:
119
- images_b64_json = encode_image_file_to_b64_json(image)
120
  except Exception as e:
121
  print(f"[图片 base64编码失败] {e}")
122
  return None, seed
123
 
124
  try:
125
  event_id = call_named_infer(
126
- images_b64_json,
127
  prompt,
128
  lora_adapter,
129
  seed,
@@ -134,7 +139,6 @@ def infer(
134
  print("API返回event_id:", event_id)
135
  data, outputs = poll_infer(event_id)
136
  print("[API 完成] data:", data, "outputs:", outputs)
137
- # 适配返回结构:outputs 是 dict(含 path/url/seed 等),或者直接 path
138
  img_out = None
139
  seed_used = seed
140
  if outputs:
@@ -153,7 +157,6 @@ def infer(
153
  img_out = API_BASE + data
154
  else:
155
  img_out = data
156
- # url 补全为完整远端URL(部分 gradio 返回 path 不是http开头)
157
  if img_out and isinstance(img_out, str) and not img_out.startswith("http"):
158
  img_out = API_BASE + img_out
159
  return img_out, int(seed_used)
 
9
  HF_TOKEN = os.environ.get("girlToken")
10
 
11
  API_BASE = "https://prithivmlmods-qwen-image-edit-2511-loras-fast.hf.space"
12
+ INFER_URL = f"{API_BASE}/gradio/infer"
13
  NAMED_API_URL = f"{API_BASE}/gradio_api/call/v2/infer"
14
 
15
  LORA_STYLES = [
 
22
  ]
23
  MAX_SEED = 2**31 - 1
24
 
25
+ def encode_image_file_to_b64_payload(image_path):
26
+ """
27
+ 返回符合API要求的图片Payload对象(list,不是json字符串)。
28
+ """
29
  try:
30
  with open(image_path, "rb") as f:
31
  image_bytes = f.read()
32
+ # 如jpeg转码
33
  try:
34
  img = Image.open(BytesIO(image_bytes))
35
  buffered = BytesIO()
 
38
  except Exception:
39
  pass
40
  im_b64 = base64.b64encode(image_bytes).decode("utf-8")
 
41
  payload = [
42
  {
43
  "data": im_b64,
 
45
  "orig_name": os.path.basename(image_path),
46
  }
47
  ]
48
+ return payload
 
49
  except Exception as e:
50
  raise RuntimeError(f"图片编码失败: {e}")
51
 
52
  def call_named_infer(
53
+ images_b64_payload,
54
  prompt,
55
  lora_adapter,
56
  seed,
 
63
  'Content-Type': 'application/json'
64
  }
65
  payload = {
66
+ "images_b64_json": images_b64_payload, # 注意此处改为直接传 list
67
  "prompt": prompt,
68
  "lora_adapter": lora_adapter,
69
  "seed": int(seed),
70
  "randomize_seed": bool(randomize_seed),
71
+ "guidance_scale": float(guidance_scale),
72
  "steps": int(steps),
73
  }
74
+ print("准备调用/infer:", {**payload, "images_b64_json": "[payload omitted for brevity]"})
75
+ import json
76
+ # 注意: 直接以json.dumps(payload)传body
77
+ resp = requests.post(NAMED_API_URL, data=json.dumps(payload), headers=headers)
78
  resp.raise_for_status()
 
79
  job = resp.json()
80
  event_id = job.get("event_id")
81
  return event_id
82
 
83
  def poll_infer(event_id):
 
84
  url = f"{API_BASE}/gradio_api/call/infer/{event_id}"
85
  headers = {'Authorization': f'Bearer {HF_TOKEN}'}
86
  import time
87
+ for i in range(60):
88
  resp = requests.get(url, headers=headers)
89
+ try:
90
+ result = resp.json()
91
+ except Exception:
92
+ print(f"[轮询第{i+1}次] 响应无法decode,返回内容:{resp.text[:200]}")
93
+ time.sleep(2)
94
+ continue
95
  if result.get("status") == "complete":
96
  return result.get("data"), result.get("outputs")
97
  elif result.get("status") == "error":
 
121
  seed = random.randint(0, MAX_SEED)
122
 
123
  try:
124
+ images_b64_payload = encode_image_file_to_b64_payload(image)
125
  except Exception as e:
126
  print(f"[图片 base64编码失败] {e}")
127
  return None, seed
128
 
129
  try:
130
  event_id = call_named_infer(
131
+ images_b64_payload,
132
  prompt,
133
  lora_adapter,
134
  seed,
 
139
  print("API返回event_id:", event_id)
140
  data, outputs = poll_infer(event_id)
141
  print("[API 完成] data:", data, "outputs:", outputs)
 
142
  img_out = None
143
  seed_used = seed
144
  if outputs:
 
157
  img_out = API_BASE + data
158
  else:
159
  img_out = data
 
160
  if img_out and isinstance(img_out, str) and not img_out.startswith("http"):
161
  img_out = API_BASE + img_out
162
  return img_out, int(seed_used)