hit-cxf
2026-05-13 0c05477d19b9df8aa6aed137927ba85312e12941
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import json
import logging
import os
import uuid
from datetime import datetime
from typing import List
 
from fastapi import APIRouter
 
from api.schemas.sandbox import (
    SandboxI2IRequest,
    SandboxLLMRequest,
    SandboxT2IRequest,
    SandboxVLMRequest,
    SandboxVideoRequest,
)
from config import settings
 
router = APIRouter(tags=["Sandbox"])
logger = logging.getLogger(__name__)
 
 
SANDBOX_DIR = os.path.join(settings.CODE_DIR, "result", "sandbox")
SANDBOX_HISTORY_FILE = os.path.join(SANDBOX_DIR, "history.json")
 
# 确保目录存在
os.makedirs(SANDBOX_DIR, exist_ok=True)
 
 
def _load_history() -> List[dict]:
    """加载历史记录"""
    if os.path.exists(SANDBOX_HISTORY_FILE):
        try:
            with open(SANDBOX_HISTORY_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception:
            logger.warning("Failed to load sandbox history: %s", SANDBOX_HISTORY_FILE, exc_info=True)
            return []
    return []
 
 
def _save_history(history: List[dict]):
    """保存历史记录"""
    with open(SANDBOX_HISTORY_FILE, 'w', encoding='utf-8') as f:
        json.dump(history, f, ensure_ascii=False, indent=2)
 
 
def _normalize_path(path: str) -> str:
    """将绝对路径转换为相对路径格式 result/..."""
    if not path:
        return path
    # 如果已经是相对路径,直接返回
    if not path.startswith('/'):
        # 确保以 result/ 开头
        if not path.startswith('result/'):
            return f"result/{path}"
        return path
    # 绝对路径,提取相对于 CODE_DIR 的部分
    code_dir = settings.CODE_DIR
    if path.startswith(code_dir):
        relative = path[len(code_dir):].lstrip('/')
        # 直接返回 result/... 格式,因为 /code/ 会映射到 CODE_DIR
        return relative
    # 其他绝对路径,尝试提取文件名
    return path.split('/')[-1]
 
 
def _convert_output_paths(output_data: dict) -> dict:
    """转换 output 中的路径为相对路径格式"""
    if not output_data:
        return output_data
    converted = output_data.copy()
    # 转换 images
    if 'images' in converted and isinstance(converted['images'], list):
        converted['images'] = [_normalize_path(img) for img in converted['images']]
    # 转换 video_path
    if 'video_path' in converted and converted['video_path']:
        converted['video_path'] = _normalize_path(converted['video_path'])
    # 转换 input 中的 reference_image
    if 'reference_image' in converted.get('input', {}):
        input_copy = converted['input'].copy()
        input_copy['reference_image'] = _normalize_path(input_copy['reference_image'])
        converted['input'] = input_copy
    return converted
 
 
def _add_record(tool: str, model: str, input_data: dict, output_data: dict, files: List[str] = None) -> str:
    """添加历史记录"""
    record_id = str(uuid.uuid4().hex[:8])
    # 转换路径为相对路径格式
    output_data = _convert_output_paths(output_data)
    record = {
        "id": record_id,
        "tool": tool,
        "model": model,
        "input": input_data,
        "output": output_data,
        "files": files or [],
        "created_at": datetime.now().isoformat(),
    }
    history = _load_history()
    history.insert(0, record)  # 最新记录放在最前面
    _save_history(history)
    return record_id
 
 
def _delete_record_files(files: List[str]):
    """删除记录关联的文件"""
    for f in files:
        if f and os.path.exists(f):
            try:
                os.remove(f)
            except Exception:
                logger.warning("Failed to delete sandbox artifact: %s", f, exc_info=True)
                pass
 
 
# 请求模型
@router.get("/api/sandbox/history")
async def sandbox_get_history():
    """获取历史记录列表"""
    history = _load_history()
    # 返回完整信息(包括 output)
    return {
        "success": True,
        "records": [
            {
                "id": r["id"],
                "tool": r["tool"],
                "model": r["model"],
                "input": r["input"],
                "output": r.get("output"),
                "created_at": r["created_at"],
            }
            for r in history
        ]
    }
 
 
@router.get("/api/sandbox/history/{record_id}")
async def sandbox_get_record(record_id: str):
    """获取单条历史记录详情"""
    history = _load_history()
    for r in history:
        if r["id"] == record_id:
            return {"success": True, "record": r}
    return {"success": False, "error": "记录不存在"}
 
 
@router.delete("/api/sandbox/history/{record_id}")
async def sandbox_delete_record(record_id: str):
    """删除历史记录"""
    history = _load_history()
    record_to_delete = None
    new_history = []
    for r in history:
        if r["id"] == record_id:
            record_to_delete = r
        else:
            new_history.append(r)
 
    if record_to_delete is None:
        return {"success": False, "error": "记录不存在"}
 
    # 删除关联的文件
    _delete_record_files(record_to_delete.get("files", []))
    _save_history(new_history)
    logger.info("Sandbox history deleted: record_id=%s", record_id)
    return {"success": True}
 
 
@router.post("/api/sandbox/llm")
async def sandbox_llm(req: SandboxLLMRequest):
    """临时工作台 - LLM 文字生成"""
    from models.llm_client import LLM
    client = LLM()
    try:
        logger.info("Sandbox LLM started: model=%s web_search=%s", req.model, req.web_search)
        result = client.query(req.prompt, model=req.model, web_search=req.web_search)
        # ��存到历史记录
        record_id = _add_record(
            tool="llm",
            model=req.model,
            input_data={"prompt": req.prompt, "web_search": req.web_search},
            output_data={"response": result}
        )
        logger.info("Sandbox LLM completed: model=%s record_id=%s", req.model, record_id)
        return {"success": True, "result": result, "record_id": record_id}
    except Exception as e:
        logger.exception("Sandbox LLM failed: model=%s", req.model)
        return {"success": False, "error": str(e)}
 
 
@router.post("/api/sandbox/vlm")
async def sandbox_vlm(req: SandboxVLMRequest):
    """临时工作台 - VLM 图片理解"""
    from models.vlm_client import VLM
    client = VLM()
    try:
        logger.info("Sandbox VLM started: model=%s images=%d", req.model, len(req.images or []))
        result = client.query(req.prompt, image_paths=req.images, model=req.model)
        # 保存到历史记录
        record_id = _add_record(
            tool="vlm",
            model=req.model,
            input_data={"prompt": req.prompt, "images": req.images},
            output_data={"response": result}
        )
        logger.info("Sandbox VLM completed: model=%s record_id=%s", req.model, record_id)
        return {"success": True, "result": result, "record_id": record_id}
    except Exception as e:
        logger.exception("Sandbox VLM failed: model=%s", req.model)
        return {"success": False, "error": str(e)}
 
 
@router.post("/api/sandbox/t2i")
async def sandbox_t2i(req: SandboxT2IRequest):
    """临时工作台 - 文生图"""
    from models.image_client import ImageClient
    client = ImageClient()
    try:
        logger.info("Sandbox T2I started: model=%s ratio=%s", req.model, req.ratio)
        result = client.generate_image(req.prompt, model=req.model, image_paths=None, video_ratio=req.ratio)
        # result 是图片路径列表
        # 保存到历史记录
        record_id = _add_record(
            tool="t2i",
            model=req.model,
            input_data={"prompt": req.prompt, "style": req.style, "ratio": req.ratio},
            output_data={"images": result},
            files=result if isinstance(result, list) else []
        )
        logger.info(
            "Sandbox T2I completed: model=%s record_id=%s images=%d",
            req.model,
            record_id,
            len(result) if isinstance(result, list) else 0,
        )
        return {"success": True, "result": result, "record_id": record_id}
    except Exception as e:
        logger.exception("Sandbox T2I failed: model=%s", req.model)
        return {"success": False, "error": str(e)}
 
 
@router.post("/api/sandbox/i2i")
async def sandbox_i2i(req: SandboxI2IRequest):
    """临时工作台 - 图生图"""
    from models.image_client import ImageClient
    client = ImageClient()
    try:
        logger.info("Sandbox I2I started: model=%s ratio=%s", req.model, req.ratio)
        result = client.generate_image(req.prompt, image_paths=[req.image], model=req.model, video_ratio=req.ratio)
        # 保存到历史记录
        record_id = _add_record(
            tool="i2i",
            model=req.model,
            input_data={"prompt": req.prompt, "reference_image": req.image},
            output_data={"images": result},
            files=result if isinstance(result, list) else []
        )
        logger.info(
            "Sandbox I2I completed: model=%s record_id=%s images=%d",
            req.model,
            record_id,
            len(result) if isinstance(result, list) else 0,
        )
        return {"success": True, "result": result, "record_id": record_id}
    except Exception as e:
        logger.exception("Sandbox I2I failed: model=%s", req.model)
        return {"success": False, "error": str(e)}
 
 
@router.post("/api/sandbox/video")
async def sandbox_video(req: SandboxVideoRequest):
    """临时工作台 - 视频生成"""
    from models.video_client import VideoClient
    client = VideoClient()
    try:
        # 生成唯一的保存路径
        save_dir = os.path.join(SANDBOX_DIR, "videos")
        os.makedirs(save_dir, exist_ok=True)
        save_path = os.path.join(save_dir, f"{uuid.uuid4().hex[:8]}.mp4")
        logger.info("Sandbox video started: model=%s image=%s", req.model, bool(req.image))
 
        result = client.generate_video(
            prompt=req.prompt,
            image_path=req.image or "",
            save_path=save_path,
            model=req.model,
            duration=5,
            shot_type="multi"
        )
        # 保存到历史记录
        record_id = _add_record(
            tool="video",
            model=req.model,
            input_data={"prompt": req.prompt, "reference_image": req.image},
            output_data={"video": result, "video_path": save_path},
            files=[save_path]
        )
        logger.info("Sandbox video completed: model=%s record_id=%s video=%s", req.model, record_id, save_path)
        return {"success": True, "result": result, "video_path": save_path, "record_id": record_id}
    except Exception as e:
        logger.exception("Sandbox video failed: model=%s", req.model)
        return {"success": False, "error": str(e)}