Skip to content

Commit 913fd57

Browse files
committed
publish
1 parent 52bd518 commit 913fd57

File tree

9 files changed

+173
-22
lines changed

9 files changed

+173
-22
lines changed

Dockerfile

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@ FROM ghcr.io/rachelos/py3.13.1:latest
44
WORKDIR /app
55

66
# ENV PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
7-
ENV PIP_INDEX_URL=https://mirrors.huaweicloud.com/repository/pypi/simple
7+
ENV PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
88

99
# 复制Python依赖文件
1010
# 复制后端代码
11-
COPY . .
1211
COPY requirements.txt .
13-
RUN pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
12+
RUN pip3 install -r requirements.txt
13+
ADD . .
1414
RUN chmod +x ./start.sh
1515
# 暴露端口
1616
EXPOSE 8081
1717
# 启动命令
18-
CMD ["./start.sh"]
18+
CMD ["./start.sh"]
19+
# CMD ["sleep", "infinity"]

README.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,4 +128,22 @@ python main.py test
128128

129129
- **URL**: `/api/download_image/{prompt_id}`
130130
- **方法**: GET
131-
- **响应**: 图像文件(PNG)
131+
- **响应**: 图像文件(PNG)
132+
133+
### 代理远程图片
134+
135+
- **URL**: `/api/proxy_image`
136+
- **方法**: GET
137+
- **参数**:
138+
- `url` (查询参数): 要代理的远程图片URL
139+
- **响应**: 图片流(支持跨域访问)
140+
- **示例**:
141+
```
142+
GET /api/proxy_image?url=https://example.com/image.jpg
143+
```
144+
- **功能特点**:
145+
- 解决跨域访问问题
146+
- 支持多种图片格式(JPEG、PNG、GIF)
147+
- 自动图片优化和压缩
148+
- 缓存机制提高性能
149+
- 支持重定向跟随

client/comfyui_client.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,16 @@ def __init__(self, server_address="http://10.10.10.59:6700",template_name="1.yam
3333
self.node_execution_times = {} # 记录节点执行时间
3434
self.task_start_time = None # 任务开始时间
3535
def get_template(self):
36-
template_path = os.path.join( "./resources/templates", self.template_name)
36+
# 获取当前文件的目录,然后构建绝对路径
37+
current_dir = os.path.dirname(os.path.abspath(__file__))
38+
project_root = os.path.dirname(current_dir)
39+
template_path = os.path.join(project_root, "resources", "templates", self.template_name)
3740
import yaml
3841
try:
3942
self.template_data = yaml.load(open(template_path, "r", encoding="utf-8"),Loader=yaml.FullLoader)
4043
except:
41-
print(os.path.abspath(template_path))
42-
raise Exception(f"模板文件不存在{template_path}")
44+
print(f"尝试加载的模板路径: {os.path.abspath(template_path)}")
45+
raise Exception(f"模板文件不存在: {template_path}")
4346
return self.template_data
4447

4548

@@ -50,9 +53,12 @@ def get_args(self,key="args"):
5053
def get_template_file(self):
5154
data=self.get_template()
5255
file=data.get("file","")
53-
file=os.path.join( "./resources/templates", file)
56+
# 获取当前文件的目录,然后构建绝对路径
57+
current_dir = os.path.dirname(os.path.abspath(__file__))
58+
project_root = os.path.dirname(current_dir)
59+
file=os.path.join(project_root, "resources", "templates", file)
5460
if not os.path.exists(file):
55-
raise Exception("模板文件不存在")
61+
raise Exception(f"模板文件不存在: {file}")
5662
with open(file, "r", encoding="utf-8") as f:
5763
workflow_template = json.load(f)
5864
return workflow_template
@@ -515,8 +521,8 @@ def get_workflows(self):
515521
templates_dir = os.path.join("./resources/templates")
516522

517523
# 使用glob模块获取所有.yml和.yaml文件
518-
yml_files = glob.glob(os.path.join(templates_dir, "*.yml"))
519-
yaml_files = glob.glob(os.path.join(templates_dir, "*.yaml"))
524+
yml_files = glob.glob(os.path.join(templates_dir, "*.yml"),recursive=True)
525+
yaml_files = glob.glob(os.path.join(templates_dir, "*.yaml"),recursive=True)
520526

521527
# 合并文件列表并只保留文件名(不含路径)
522528
workflow_files = []

dock_build.bat

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ REM 获取所有运行中容器的ID并逐个停止
77
FOR /f "tokens=*" %%i IN ('docker ps -q') DO docker stop %%i
88
docker container prune -f
99

10-
docker run -d --name %name% -p 8002:8081 -e COMFYUI_SERVER=http://10.10.10.54:6700 %name%
10+
docker run -d --name %name% -p 8002:8081 -e COMFYUI_SERVER=http://10.10.10.54:6700 -v %~dp0:/work %name%
1111
docker exec -it %name% /bin/bash
1212

1313
if "%1"=="-p" (

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ click==8.3.1
77
colorama==0.4.6
88
fastapi==0.122.0
99
h11==0.16.0
10+
httpcore==1.0.9
11+
httpx==0.28.1
1012
idna==3.11
1113
pillow==12.0.0
1214
pydantic==2.12.5

routes/image_routes.py

Lines changed: 80 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
from fastapi import APIRouter
22
from pydantic import BaseModel
33
from core.image_generator import get_image_generator
4-
from fastapi.responses import FileResponse
5-
from fastapi import HTTPException
4+
from fastapi.responses import FileResponse, StreamingResponse
5+
from fastapi import HTTPException, Query
6+
import httpx
7+
import io
8+
from PIL import Image
9+
import logging
610

711
router = APIRouter(prefix="/api", tags=["Image Generation"])
812
image_generator = get_image_generator()
913
class ImageGenerationRequest(BaseModel):
1014
prompt: str = ""
1115
negative_prompt: str = ""
12-
workflow: str = "1.yml"
16+
workflow: str = "1.yaml"
1317
width: int = 512
1418
height: int = 512
1519
batch_size: int = 4
@@ -67,3 +71,76 @@ async def get_workflows():
6771
return data
6872
except Exception as e:
6973
raise HTTPException(status_code=404, detail=f"获取文件失败: {str(e)}")
74+
75+
@router.get("/proxy_image")
76+
async def proxy_image(url: str = Query(..., description="要代理的远程图片URL")):
77+
"""
78+
代理远程图片资源
79+
80+
通过代理访问远程图片,解决跨域问题
81+
"""
82+
try:
83+
# 设置请求头,模拟浏览器访问
84+
headers = {
85+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
86+
"Accept": "image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
87+
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
88+
"Accept-Encoding": "gzip, deflate, br",
89+
"Connection": "keep-alive",
90+
"Upgrade-Insecure-Requests": "1",
91+
}
92+
93+
# 使用httpx客户端获取远程图片
94+
with httpx.Client(timeout=30.0, follow_redirects=True) as client:
95+
response = client.get(url, headers=headers)
96+
response.raise_for_status()
97+
98+
# 检查响应内容类型
99+
content_type = response.headers.get("content-type", "")
100+
if not content_type.startswith("image/"):
101+
raise HTTPException(status_code=400, detail="URL不是有效的图片资源")
102+
103+
# 获取图片数据
104+
image_data = response.content
105+
106+
# 尝试使用PIL验证图片格式
107+
try:
108+
image = Image.open(io.BytesIO(image_data))
109+
# 重新保存为JPEG格式(可根据需要调整)
110+
img_buffer = io.BytesIO()
111+
112+
# 根据原始格式选择保存格式
113+
if image.format == "PNG":
114+
image.save(img_buffer, format="PNG", quality=95)
115+
content_type = "image/png"
116+
elif image.format == "GIF":
117+
image.save(img_buffer, format="GIF")
118+
content_type = "image/gif"
119+
else:
120+
image.save(img_buffer, format="JPEG", quality=95, optimize=True)
121+
content_type = "image/jpeg"
122+
123+
img_buffer.seek(0)
124+
image_data = img_buffer.getvalue()
125+
126+
except Exception as img_error:
127+
logging.warning(f"图片处理失败,直接返回原始数据: {img_error}")
128+
129+
# 返回图片流响应
130+
return StreamingResponse(
131+
io.BytesIO(image_data),
132+
media_type=content_type,
133+
headers={
134+
"Cache-Control": "public, max-age=3600", # 缓存1小时
135+
"Access-Control-Allow-Origin": "*", # 允许跨域
136+
"Access-Control-Allow-Methods": "GET",
137+
"Access-Control-Allow-Headers": "*",
138+
}
139+
)
140+
141+
except httpx.HTTPStatusError as e:
142+
raise HTTPException(status_code=e.response.status_code, detail=f"获取远程图片失败: {e.response.status_code}")
143+
except httpx.RequestError as e:
144+
raise HTTPException(status_code=500, detail=f"请求远程图片失败: {str(e)}")
145+
except Exception as e:
146+
raise HTTPException(status_code=500, detail=f"代理图片失败: {str(e)}")

start.sh

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
11
#!/bin/bash
22
cd /app/
3-
pwd
3+
pip3 install -r requirements.txt
44
python3 app.py
5-
# 执行一些操作...
6-
while true; do
7-
sleep 10
8-
done

test_proxy_image.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
测试图片代理功能
6+
"""
7+
8+
import requests
9+
import json
10+
11+
def test_proxy_image():
12+
"""测试图片代理API"""
13+
base_url = "http://localhost:8081"
14+
15+
# 测试用的远程图片URL
16+
test_urls = [
17+
"https://picsum.photos/200/300",
18+
"https://via.placeholder.com/150x150/0000FF/808080?text=Test",
19+
"https://httpbin.org/image/png"
20+
]
21+
22+
for i, url in enumerate(test_urls):
23+
print(f"\n测试图片 {i+1}: {url}")
24+
25+
try:
26+
# 调用代理API
27+
response = requests.get(
28+
f"{base_url}/api/proxy_image",
29+
params={"url": url},
30+
timeout=30
31+
)
32+
33+
print(f"状态码: {response.status_code}")
34+
print(f"响应头: {dict(response.headers)}")
35+
36+
if response.status_code == 200:
37+
# 保存代理后的图片
38+
with open(f"proxied_image_{i+1}.jpg", "wb") as f:
39+
f.write(response.content)
40+
print(f"图片已保存为: proxied_image_{i+1}.jpg")
41+
print(f"图片大小: {len(response.content)} bytes")
42+
else:
43+
print(f"错误: {response.text}")
44+
45+
except Exception as e:
46+
print(f"请求失败: {e}")
47+
48+
if __name__ == "__main__":
49+
print("开始测试图片代理功能...")
50+
print("请确保服务器运行在 http://localhost:8081")
51+
test_proxy_image()

web_ui/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ <h2>创建您的AI艺术</h2>
307307
<span class="label-icon">🔢</span>
308308
数量:
309309
</label>
310-
<input type="number" id="batch_size" value="2" min="1" max="4">
310+
<input type="number" id="batch_size" value="1" min="1" max="4">
311311
</div>
312312
</div>
313313

0 commit comments

Comments
 (0)