kenfoo commited on
Commit
9c3af51
·
verified ·
1 Parent(s): 2bed509

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -73
app.py CHANGED
@@ -1,16 +1,14 @@
1
  import gradio as gr
2
- from gradio_client import Client
3
  import random
4
  import os
5
- import requests
6
- import tempfile
7
 
8
  HF_TOKEN = os.environ.get("girlToken")
9
 
10
  space_client = Client(
11
  "prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast",
12
- token=HF_TOKEN
13
- )
14
 
15
  LORA_STYLES = [
16
  'Multiple-Angles', 'Photo-to-Anime', 'Anime-V2', 'Light-Migration',
@@ -23,44 +21,6 @@ LORA_STYLES = [
23
  MAX_SEED = 2**31 - 1
24
 
25
 
26
- # def upload_to_imgbb(image_path):
27
- # """上传图片到免费图床,返回公开 URL"""
28
- # IMGBB_API_KEY = os.environ.get("IMGBB_API_KEY")
29
- # if not IMGBB_API_KEY:
30
- # return None
31
- # with open(image_path, "rb") as f:
32
- # import base64
33
- # b64 = base64.b64encode(f.read()).decode()
34
- # resp = requests.post(
35
- # "https://api.imgbb.com/1/upload",
36
- # data={"key": IMGBB_API_KEY, "image": b64}
37
- # )
38
- # if resp.status_code == 200:
39
- # print(f'图床resp.json()={resp.json()}')
40
- # return resp.json()["data"]["url"]
41
- # return None
42
-
43
- def upload_to_hf(image_path):
44
- """上传到 HF dataset,返回公开直链"""
45
- from huggingface_hub import HfApi
46
- import uuid
47
-
48
- api = HfApi(token=HF_TOKEN)
49
- filename = f"{uuid.uuid4().hex[:8]}_{os.path.basename(image_path)}"
50
-
51
- # 上传到你自己的 HF dataset repo(需要先创建一个 public dataset repo)
52
- url = api.upload_file(
53
- path_or_fileobj=image_path,
54
- path_in_repo=f"uploads/{filename}",
55
- repo_id="kenfoo", # 改成你自己的
56
- repo_type="dataset",
57
- )
58
- print(f'图床 ={url}')
59
- # 转成直链格式
60
- # url 格式: https://huggingface.co/datasets/xxx/yyy/resolve/main/uploads/zzz.jpg
61
- return url
62
-
63
-
64
  def infer(
65
  image,
66
  prompt,
@@ -71,29 +31,39 @@ def infer(
71
  steps,
72
  progress=gr.Progress(track_tqdm=True),
73
  ):
74
- if image is None or not os.path.exists(image):
75
  print("未上传图片")
76
  return None, seed
77
 
 
 
 
 
78
  if randomize_seed:
79
  seed = random.randint(0, MAX_SEED)
80
 
81
- # 方案:上传到公开图床 URL 再传给远端
82
- #public_url = upload_to_imgbb(image)
83
-
84
- public_url = upload_to_hf(image)
85
 
86
- if not public_url:
87
- print("图床上传失败 ")
88
- return None, seed
 
 
89
 
90
- print(f"图片公开 URL: {public_url}")
91
 
92
- # 直接URL 字符串,让远端自己下载
93
- # 直接传字符串列表
94
- images_input = [public_url]
95
 
96
- print(f"prompt: {prompt}, lora: {lora_adapter}, seed: {seed}")
 
 
 
 
 
 
 
97
 
98
  try:
99
  result = space_client.predict(
@@ -107,18 +77,21 @@ def infer(
107
  api_name="/infer",
108
  )
109
 
110
- print(f"返回值: {result}")
 
111
  image_info, seed_used = result
 
112
  if isinstance(image_info, dict):
113
  img_out = image_info.get("path") or image_info.get("url")
114
  else:
115
  img_out = image_info
 
116
  return img_out, int(seed_used)
117
 
118
  except Exception as e:
119
  import traceback
120
  traceback.print_exc()
121
- print(f"异常: {e}")
122
  return None, seed
123
 
124
 
@@ -133,17 +106,50 @@ with gr.Blocks(css=css) as demo:
133
  with gr.Column(elem_id="col-container"):
134
  gr.Markdown("# 图像编辑 Demo\n基于 prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast")
135
 
136
- image = gr.Image(label="上传图片", sources=["upload"], type="filepath")
137
- prompt = gr.Text(label="编辑描述(Prompt)", placeholder="请输入图片编辑描述...")
138
- lora_adapter = gr.Dropdown(label="编辑风格(Style)", choices=LORA_STYLES, value="Photo-to-Anime")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  run_button = gr.Button("执行编辑", variant="primary")
140
- result = gr.Image(label="结果图片")
 
141
 
142
  with gr.Accordion("高级设置", open=False):
143
- seed = gr.Slider(label="随机种子", minimum=0, maximum=MAX_SEED, step=1, value=0)
 
 
 
 
 
 
144
  randomize_seed = gr.Checkbox(label="随机化种子", value=True)
145
- guidance_scale = gr.Slider(label="引导强度", minimum=0.1, maximum=10.0, step=0.1, value=1.0)
146
- steps = gr.Slider(label="推理步数", minimum=1, maximum=50, step=1, value=4)
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  gr.on(
149
  triggers=[run_button.click, prompt.submit],
@@ -153,11 +159,4 @@ with gr.Blocks(css=css) as demo:
153
  )
154
 
155
  if __name__ == "__main__":
156
- demo.launch(ssr_mode=False, share=True)
157
- # ```
158
-
159
- # 然后去 [imgbb.com](https://imgbb.com/api) 免费申请一个 API key,存到 HF Space 的 Secrets 里,变量名 `IMGBB_API_KEY`。
160
-
161
- # 这样的流程是:
162
- # ```
163
-
 
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',
 
21
  MAX_SEED = 2**31 - 1
22
 
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  def infer(
25
  image,
26
  prompt,
 
31
  steps,
32
  progress=gr.Progress(track_tqdm=True),
33
  ):
34
+ if image is None:
35
  print("未上传图片")
36
  return None, seed
37
 
38
+ if not os.path.exists(image):
39
+ print(f"图片路径不存在: {image}")
40
+ return None, seed
41
+
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(
 
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
 
 
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="上传图片",
111
+ sources=["upload"],
112
+ type="filepath",
113
+ )
114
+
115
+ prompt = gr.Text(
116
+ label="编辑描述(Prompt)",
117
+ placeholder="请输入图片编辑描述...",
118
+ )
119
+
120
+ lora_adapter = gr.Dropdown(
121
+ label="编辑��格(Style)",
122
+ choices=LORA_STYLES,
123
+ value="Photo-to-Anime"
124
+ )
125
+
126
  run_button = gr.Button("执行编辑", variant="primary")
127
+
128
+ result = gr.Image(label="结果图片", show_label=True)
129
 
130
  with gr.Accordion("高级设置", open=False):
131
+ seed = gr.Slider(
132
+ label="随机种子",
133
+ minimum=0,
134
+ maximum=MAX_SEED,
135
+ step=1,
136
+ value=0,
137
+ )
138
  randomize_seed = gr.Checkbox(label="随机化种子", value=True)
139
+ guidance_scale = gr.Slider(
140
+ label="引导强度 (Guidance Scale)",
141
+ minimum=0.1,
142
+ maximum=10.0,
143
+ step=0.1,
144
+ value=1.0,
145
+ )
146
+ steps = gr.Slider(
147
+ label="推理步数 (Steps)",
148
+ minimum=1,
149
+ maximum=50,
150
+ step=1,
151
+ value=4,
152
+ )
153
 
154
  gr.on(
155
  triggers=[run_button.click, prompt.submit],
 
159
  )
160
 
161
  if __name__ == "__main__":
162
+ demo.launch(ssr_mode=False, share=True)