kenfoo commited on
Commit
ca9155f
·
verified ·
1 Parent(s): 1d9be8e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -21
app.py CHANGED
@@ -1,66 +1,114 @@
1
- import requests
2
- import os
3
  import gradio as gr
4
- from gradio_client import Client, handle_file
5
  import random
6
-
 
7
 
8
  HF_TOKEN = os.environ.get("girlToken")
9
  TARGET_SPACE_URL = "https://prithivmlmods-qwen-image-edit-2511-loras-fast.hf.space"
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def upload_file_to_space(local_path):
12
- """手动上传文件到目标 Space,返回远端 URL"""
13
  upload_url = f"{TARGET_SPACE_URL}/upload"
14
-
15
  headers = {}
16
  if HF_TOKEN:
17
  headers["Authorization"] = f"Bearer {HF_TOKEN}"
18
-
 
 
 
 
 
 
19
  with open(local_path, "rb") as f:
20
  response = requests.post(
21
  upload_url,
22
  headers=headers,
23
- files={"files": (os.path.basename(local_path), f, "image/jpeg")},
24
  )
25
-
26
  print(f"上传状态码: {response.status_code}")
27
  print(f"上传响应: {response.text}")
28
-
29
  if response.status_code == 200:
30
  result = response.json()
31
- # 返回的是文件路径列表,取第一个
32
  remote_path = result[0] if isinstance(result, list) else result
33
  return remote_path
34
  else:
35
  raise Exception(f"上传失败: {response.status_code} {response.text}")
36
 
37
 
38
- def infer(image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps, progress=gr.Progress(track_tqdm=True)):
39
- if image is None or not os.path.exists(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  return None, seed
41
 
42
  if randomize_seed:
43
  seed = random.randint(0, MAX_SEED)
44
 
45
- # 手动上传,拿到远端路径
46
- remote_path = upload_file_to_space(image)
47
- print(f"远端路径: {remote_path}")
 
 
 
 
 
 
 
 
 
48
 
49
- # 用远端路径构造 images 参数
50
  images_input = [{
51
  "image": {
52
  "path": remote_path,
53
  "url": f"{TARGET_SPACE_URL}/file={remote_path}",
54
  "size": os.path.getsize(image),
55
  "orig_name": os.path.basename(image),
56
- "mime_type": "image/jpeg",
57
  "is_stream": False,
58
  "meta": {}
59
  },
60
  "caption": None
61
  }]
62
 
63
- print(f"images_input: {images_input}")
 
 
 
 
 
 
64
 
65
  try:
66
  result = space_client.predict(
@@ -74,12 +122,86 @@ def infer(image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, ste
74
  api_name="/infer",
75
  )
76
 
 
 
77
  image_info, seed_used = result
78
- img_out = image_info.get("path") or image_info.get("url")
 
 
 
 
 
79
  return img_out, int(seed_used)
80
 
81
  except Exception as e:
82
  import traceback
83
  traceback.print_exc()
84
  print(f"[调用API] 异常: {e}")
85
- return None, seed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from gradio_client import Client
3
  import random
4
+ import os
5
+ import requests
6
 
7
  HF_TOKEN = os.environ.get("girlToken")
8
  TARGET_SPACE_URL = "https://prithivmlmods-qwen-image-edit-2511-loras-fast.hf.space"
9
 
10
+ space_client = Client(
11
+ "prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast",
12
+ hf_token=HF_TOKEN
13
+ )
14
+
15
+ LORA_STYLES = [
16
+ 'Multiple-Angles', 'Photo-to-Anime', 'Anime-V2', 'Light-Migration',
17
+ 'Upscaler', 'Style-Transfer', 'Manga-Tone', 'Anything2Real',
18
+ 'Fal-Multiple-Angles', 'Polaroid-Photo', 'Unblur-Anything',
19
+ 'Midnight-Noir-Eyes-Spotlight', 'Hyper-Realistic-Portrait',
20
+ 'Ultra-Realistic-Portrait', 'Pixar-Inspired-3D', 'Noir-Comic-Book',
21
+ 'Any-light', 'Studio-DeLight', 'Cinematic-FlatLog',
22
+ ]
23
+ MAX_SEED = 2**31 - 1
24
+
25
+
26
  def upload_file_to_space(local_path):
27
+ """手动上传文件到目标 Space,返回远端路径"""
28
  upload_url = f"{TARGET_SPACE_URL}/upload"
29
+
30
  headers = {}
31
  if HF_TOKEN:
32
  headers["Authorization"] = f"Bearer {HF_TOKEN}"
33
+
34
+ mime_type = "image/jpeg"
35
+ if local_path.lower().endswith(".png"):
36
+ mime_type = "image/png"
37
+ elif local_path.lower().endswith(".webp"):
38
+ mime_type = "image/webp"
39
+
40
  with open(local_path, "rb") as f:
41
  response = requests.post(
42
  upload_url,
43
  headers=headers,
44
+ files={"files": (os.path.basename(local_path), f, mime_type)},
45
  )
46
+
47
  print(f"上传状态码: {response.status_code}")
48
  print(f"上传响应: {response.text}")
49
+
50
  if response.status_code == 200:
51
  result = response.json()
 
52
  remote_path = result[0] if isinstance(result, list) else result
53
  return remote_path
54
  else:
55
  raise Exception(f"上传失败: {response.status_code} {response.text}")
56
 
57
 
58
+ def infer(
59
+ image,
60
+ prompt,
61
+ lora_adapter,
62
+ seed,
63
+ randomize_seed,
64
+ guidance_scale,
65
+ steps,
66
+ progress=gr.Progress(track_tqdm=True),
67
+ ):
68
+ if image is None:
69
+ print("未上传图片")
70
+ return None, seed
71
+
72
+ if not os.path.exists(image):
73
+ print(f"图片路径不存在: {image}")
74
  return None, seed
75
 
76
  if randomize_seed:
77
  seed = random.randint(0, MAX_SEED)
78
 
79
+ try:
80
+ remote_path = upload_file_to_space(image)
81
+ print(f"远端路径: {remote_path}")
82
+ except Exception as e:
83
+ print(f"上传图片失败: {e}")
84
+ return None, seed
85
+
86
+ mime_type = "image/jpeg"
87
+ if image.lower().endswith(".png"):
88
+ mime_type = "image/png"
89
+ elif image.lower().endswith(".webp"):
90
+ mime_type = "image/webp"
91
 
 
92
  images_input = [{
93
  "image": {
94
  "path": remote_path,
95
  "url": f"{TARGET_SPACE_URL}/file={remote_path}",
96
  "size": os.path.getsize(image),
97
  "orig_name": os.path.basename(image),
98
+ "mime_type": mime_type,
99
  "is_stream": False,
100
  "meta": {}
101
  },
102
  "caption": None
103
  }]
104
 
105
+ print("[调用API] 输入参数:")
106
+ print(f" remote_path: {remote_path}")
107
+ print(f" prompt: {prompt}")
108
+ print(f" lora_adapter: {lora_adapter}")
109
+ print(f" seed: {seed}")
110
+ print(f" guidance_scale: {guidance_scale}")
111
+ print(f" steps: {steps}")
112
 
113
  try:
114
  result = space_client.predict(
 
122
  api_name="/infer",
123
  )
124
 
125
+ print(f"[调用API] 返回值: {result}")
126
+
127
  image_info, seed_used = result
128
+
129
+ if isinstance(image_info, dict):
130
+ img_out = image_info.get("path") or image_info.get("url")
131
+ else:
132
+ img_out = image_info
133
+
134
  return img_out, int(seed_used)
135
 
136
  except Exception as e:
137
  import traceback
138
  traceback.print_exc()
139
  print(f"[调用API] 异常: {e}")
140
+ return None, seed
141
+
142
+
143
+ css = """
144
+ #col-container {
145
+ margin: 0 auto;
146
+ max-width: 640px;
147
+ }
148
+ """
149
+
150
+ with gr.Blocks(css=css) as demo:
151
+ with gr.Column(elem_id="col-container"):
152
+ gr.Markdown("# 图像编辑 Demo\n基于 prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast")
153
+
154
+ image = gr.Image(
155
+ label="上传图片",
156
+ sources=["upload"],
157
+ type="filepath",
158
+ )
159
+
160
+ prompt = gr.Text(
161
+ label="编辑描述(Prompt)",
162
+ placeholder="请输入图片编辑描述...",
163
+ )
164
+
165
+ lora_adapter = gr.Dropdown(
166
+ label="编辑风格(Style)",
167
+ choices=LORA_STYLES,
168
+ value="Photo-to-Anime"
169
+ )
170
+
171
+ run_button = gr.Button("执行编辑", variant="primary")
172
+
173
+ result = gr.Image(label="结果图片", show_label=True)
174
+
175
+ with gr.Accordion("高级设置", open=False):
176
+ seed = gr.Slider(
177
+ label="随机种子",
178
+ minimum=0,
179
+ maximum=MAX_SEED,
180
+ step=1,
181
+ value=0,
182
+ )
183
+ randomize_seed = gr.Checkbox(label="随机化种子", value=True)
184
+ guidance_scale = gr.Slider(
185
+ label="引导强度 (Guidance Scale)",
186
+ minimum=0.1,
187
+ maximum=10.0,
188
+ step=0.1,
189
+ value=1.0,
190
+ )
191
+ steps = gr.Slider(
192
+ label="推理步数 (Steps)",
193
+ minimum=1,
194
+ maximum=50,
195
+ step=1,
196
+ value=4,
197
+ )
198
+
199
+ gr.on(
200
+ triggers=[run_button.click, prompt.submit],
201
+ fn=infer,
202
+ inputs=[image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps],
203
+ outputs=[result, seed],
204
+ )
205
+
206
+ if __name__ == "__main__":
207
+ demo.launch(ssr_mode=False, share=True)