ZHIWEI666 commited on
Commit
7b79f99
·
verified ·
1 Parent(s): 04b9634

Upload 5 files

Browse files
Files changed (4) hide show
  1. Dockerfile +3 -2
  2. app.py +52 -2
  3. models.py +2 -0
  4. router_prompts.py +10 -0
Dockerfile CHANGED
@@ -4,11 +4,12 @@ FROM python:3.9-slim
4
  # 设置工作目录
5
  WORKDIR /code
6
 
7
- # 安装系统依赖 (psycopg2 需要)
8
  RUN apt-get update && apt-get install -y --no-install-recommends \
9
  libpq-dev \
10
  ca-certificates \
11
  libssl-dev \
 
12
  && rm -rf /var/lib/apt/lists/*
13
 
14
  # 先复制依赖文件,利用 Docker 缓存层
@@ -25,7 +26,7 @@ USER appuser
25
  # 健康检查
26
  HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/health')" || exit 1
27
 
28
- # force rebuild: 2026-05-22
29
 
30
  # 启动命令
31
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
4
  # 设置工作目录
5
  WORKDIR /code
6
 
7
+ # 安装系统依赖 (psycopg2 需要;ffmpeg 用于音频上传重编码净化)
8
  RUN apt-get update && apt-get install -y --no-install-recommends \
9
  libpq-dev \
10
  ca-certificates \
11
  libssl-dev \
12
+ ffmpeg \
13
  && rm -rf /var/lib/apt/lists/*
14
 
15
  # 先复制依赖文件,利用 Docker 缓存层
 
26
  # 健康检查
27
  HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/health')" || exit 1
28
 
29
+ # force rebuild: 2026-08-16
30
 
31
  # 启动命令
32
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py CHANGED
@@ -15,6 +15,7 @@ import json
15
  import mimetypes
16
  import logging
17
  import time
 
18
  import datetime
19
  import 数据库连接 as db
20
  import asyncio
@@ -341,6 +342,45 @@ def proxy_hf_image(url: str = None, path: str = None):
341
  # ==========================================
342
  from image_moderation import moderate_image_sync, ModerationResult
343
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  @app.post("/api/upload")
345
  def upload_file(file: UploadFile = File(...), file_type: str = Form(...), current_user: str = Depends(require_auth)):
346
  content = file.file.read()
@@ -363,6 +403,8 @@ def upload_file(file: UploadFile = File(...), file_type: str = Form(...), curren
363
  max_size = 10 * 1024 * 1024 # 其他图片: 10MB
364
  elif file_type == "post_video":
365
  max_size = 100 * 1024 * 1024
 
 
366
 
367
  if len(content) > max_size:
368
  raise HTTPException(status_code=400, detail=f"文件过大,{file_type} 类型请限制在 {max_size // (1024*1024)}MB 以内")
@@ -373,8 +415,16 @@ def upload_file(file: UploadFile = File(...), file_type: str = Form(...), curren
373
  allowed_exts = ["jpg", "jpeg", "png", "gif", "webp", "json", "mp4"]
374
  if file_type == "post_video":
375
  allowed_exts = ["mp4", "webm", "mov"]
 
 
376
  if ext not in allowed_exts:
377
  raise HTTPException(status_code=400, detail=f"不支持的文件格式,{file_type} 类型仅支持 {', '.join(allowed_exts)}")
 
 
 
 
 
 
378
 
379
  # 📝 审计日志:记录上传操作
380
  logger.info(f"UPLOAD | account={current_user} | filename={file.filename} | file_type={file_type}")
@@ -388,8 +438,8 @@ def upload_file(file: UploadFile = File(...), file_type: str = Form(...), curren
388
  detail=f"图片内容审核未通过:{moderation_result.label or '内容不合规'}"
389
  )
390
 
391
- if file_type == "post_video":
392
- safe_filename = f"post_video_{uuid.uuid4().hex[:8]}.{ext}"
393
  else:
394
  file_hash = hashlib.md5(content).hexdigest()[:10]
395
  safe_filename = f"{file_type}_{file_hash}.{ext}"
 
15
  import mimetypes
16
  import logging
17
  import time
18
+ import subprocess
19
  import datetime
20
  import 数据库连接 as db
21
  import asyncio
 
342
  # ==========================================
343
  from image_moderation import moderate_image_sync, ModerationResult
344
 
345
+ # ==========================================
346
+ # 🎵 音频安全净化:重编码压缩,剥离元数据与隐藏附加信息
347
+ # ==========================================
348
+ AUDIO_TRANSCODE_ARGS = {
349
+ "mp3": ["-acodec", "libmp3lame", "-b:a", "192k"],
350
+ "wav": ["-acodec", "pcm_s16le", "-ar", "44100"],
351
+ "m4a": ["-acodec", "aac", "-b:a", "192k"],
352
+ "ogg": ["-acodec", "libvorbis", "-b:a", "192k"],
353
+ }
354
+
355
+ def sanitize_audio_content(content: bytes, ext: str) -> bytes:
356
+ """🔒 用 ffmpeg 重编码压缩音频并剥离元数据/隐藏附加信息;处理失败一律拒绝上传,保障平台安全"""
357
+ src_path = f"/tmp/audio_src_{uuid.uuid4().hex[:8]}.{ext}"
358
+ dst_path = f"/tmp/audio_dst_{uuid.uuid4().hex[:8]}.{ext}"
359
+ try:
360
+ with open(src_path, "wb") as f:
361
+ f.write(content)
362
+ cmd = ["ffmpeg", "-y", "-i", src_path, "-vn", "-map_metadata", "-1", "-fflags", "+bitexact"] \
363
+ + AUDIO_TRANSCODE_ARGS[ext] + [dst_path]
364
+ try:
365
+ result = subprocess.run(cmd, capture_output=True, timeout=120)
366
+ except subprocess.TimeoutExpired:
367
+ logger.error(f"AUDIO_SANITIZE_TIMEOUT | ext={ext}")
368
+ raise HTTPException(status_code=400, detail="音频处理超时,请上传更短的音频")
369
+ if result.returncode != 0:
370
+ logger.error(f"AUDIO_SANITIZE_FAIL | ext={ext} | {result.stderr[-500:]}")
371
+ raise HTTPException(status_code=400, detail="音频文件解析失败,请转换格式后重新上传")
372
+ with open(dst_path, "rb") as f:
373
+ sanitized = f.read()
374
+ if not sanitized:
375
+ raise HTTPException(status_code=400, detail="音频处理结果为空,请重新上传")
376
+ logger.info(f"AUDIO_SANITIZE_OK | ext={ext} | {len(content)} -> {len(sanitized)} bytes")
377
+ return sanitized
378
+ finally:
379
+ for p in (src_path, dst_path):
380
+ if os.path.exists(p):
381
+ os.remove(p)
382
+
383
+
384
  @app.post("/api/upload")
385
  def upload_file(file: UploadFile = File(...), file_type: str = Form(...), current_user: str = Depends(require_auth)):
386
  content = file.file.read()
 
403
  max_size = 10 * 1024 * 1024 # 其他图片: 10MB
404
  elif file_type == "post_video":
405
  max_size = 100 * 1024 * 1024
406
+ elif file_type == "post_audio":
407
+ max_size = 30 * 1024 * 1024 # 音乐提示词音频:30MB
408
 
409
  if len(content) > max_size:
410
  raise HTTPException(status_code=400, detail=f"文件过大,{file_type} 类型请限制在 {max_size // (1024*1024)}MB 以内")
 
415
  allowed_exts = ["jpg", "jpeg", "png", "gif", "webp", "json", "mp4"]
416
  if file_type == "post_video":
417
  allowed_exts = ["mp4", "webm", "mov"]
418
+ elif file_type == "post_audio":
419
+ allowed_exts = ["mp3", "wav", "m4a", "ogg"]
420
  if ext not in allowed_exts:
421
  raise HTTPException(status_code=400, detail=f"不支持的文件格式,{file_type} 类型仅支持 {', '.join(allowed_exts)}")
422
+
423
+ # 🔒 音频安全净化:重编码压缩,剥离可能附带的元数据与隐藏附加信息
424
+ if file_type == "post_audio":
425
+ content = sanitize_audio_content(content, ext)
426
+ if len(content) > max_size:
427
+ raise HTTPException(status_code=400, detail=f"音频处理后仍超过 {max_size // (1024*1024)}MB 限制,请上传更短的音频")
428
 
429
  # 📝 审计日志:记录上传操作
430
  logger.info(f"UPLOAD | account={current_user} | filename={file.filename} | file_type={file_type}")
 
438
  detail=f"图片内容审核未通过:{moderation_result.label or '内容不合规'}"
439
  )
440
 
441
+ if file_type in ("post_video", "post_audio"):
442
+ safe_filename = f"{file_type}_{uuid.uuid4().hex[:8]}.{ext}"
443
  else:
444
  file_hash = hashlib.md5(content).hexdigest()[:10]
445
  safe_filename = f"{file_type}_{file_hash}.{ext}"
models.py CHANGED
@@ -277,6 +277,7 @@ class PromptCreate(BaseModel):
277
  cover_image: str # 封面图
278
  media_type: str = "image" # "image" 或 "video"(示例媒体类型)
279
  video_url: Optional[str] = None # 示例视频 URL(仅 media_type=video)
 
280
  images: Optional[List[str]] = None # 图像提示词图片列表(最多9张,首张为封面)
281
  is_original: bool = False # 原创作品标记
282
  price: int = 0 # 定价(0=免费)
@@ -291,6 +292,7 @@ class PromptUpdate(BaseModel):
291
  cover_image: Optional[str] = None
292
  media_type: Optional[str] = None
293
  video_url: Optional[str] = None
 
294
  images: Optional[List[str]] = None # 图像提示词图片列表(最多9张,首张为封面)
295
  is_original: Optional[bool] = None # 原创作品标记
296
  price: Optional[int] = None
 
277
  cover_image: str # 封面图
278
  media_type: str = "image" # "image" 或 "video"(示例媒体类型)
279
  video_url: Optional[str] = None # 示例视频 URL(仅 media_type=video)
280
+ audio_url: Optional[str] = None # 示例音频 URL(仅音乐提示词,图片+音频方案;视频可选)
281
  images: Optional[List[str]] = None # 图像提示词图片列表(最多9张,首张为封面)
282
  is_original: bool = False # 原创作品标记
283
  price: int = 0 # 定价(0=免费)
 
292
  cover_image: Optional[str] = None
293
  media_type: Optional[str] = None
294
  video_url: Optional[str] = None
295
+ audio_url: Optional[str] = None # 示例音频 URL(仅音乐提示词;传 null 表示清除)
296
  images: Optional[List[str]] = None # 图像提示词图片列表(最多9张,首张为封面)
297
  is_original: Optional[bool] = None # 原创作品标记
298
  price: Optional[int] = None
router_prompts.py CHANGED
@@ -460,6 +460,11 @@ async def create_prompt(prompt: PromptCreate, current_user: str = Depends(requir
460
  # 图像提示词的图片列表(首张即封面);视频提示词不保留图片列表
461
  images = _sanitize_images(prompt.images) if media_type == "image" else []
462
 
 
 
 
 
 
463
  new_prompt = {
464
  "id": f"prompt_{int(time.time())}_{uuid.uuid4().hex[:6]}",
465
  "prompt_type": prompt.prompt_type,
@@ -470,6 +475,7 @@ async def create_prompt(prompt: PromptCreate, current_user: str = Depends(requir
470
  "cover_image": prompt.cover_image,
471
  "media_type": media_type,
472
  "video_url": video_url,
 
473
  "images": images,
474
  "is_original": bool(prompt.is_original),
475
  "price": price,
@@ -567,6 +573,10 @@ async def update_prompt(prompt_id: str, update_data: PromptUpdate, current_user:
567
  prompt["video_url"] = update_data.video_url
568
  if update_data.video_url:
569
  prompt["media_type"] = "video"
 
 
 
 
570
  # 类型变更后补正关联字段(pydantic 无法区分未传与 null,统一在此收尾)
571
  if prompt.get("media_type") == "image":
572
  prompt["video_url"] = None
 
460
  # 图像提示词的图片列表(首张即封面);视频提示词不保留图片列表
461
  images = _sanitize_images(prompt.images) if media_type == "image" else []
462
 
463
+ # 🎵 音乐提示词支持音频示例(图片+音频方案,视频可选);非音乐类型不保留
464
+ audio_url = (prompt.audio_url or "").strip() or None
465
+ if prompt.prompt_type != "music":
466
+ audio_url = None
467
+
468
  new_prompt = {
469
  "id": f"prompt_{int(time.time())}_{uuid.uuid4().hex[:6]}",
470
  "prompt_type": prompt.prompt_type,
 
475
  "cover_image": prompt.cover_image,
476
  "media_type": media_type,
477
  "video_url": video_url,
478
+ "audio_url": audio_url,
479
  "images": images,
480
  "is_original": bool(prompt.is_original),
481
  "price": price,
 
573
  prompt["video_url"] = update_data.video_url
574
  if update_data.video_url:
575
  prompt["media_type"] = "video"
576
+ if update_data.audio_url is not None:
577
+ # 🎵 音频仅音乐提示词保留;传空字符串/null 表示清除
578
+ audio_url = (update_data.audio_url or "").strip() or None
579
+ prompt["audio_url"] = audio_url if prompt.get("prompt_type") == "music" else None
580
  # 类型变更后补正关联字段(pydantic 无法区分未传与 null,统一在此收尾)
581
  if prompt.get("media_type") == "image":
582
  prompt["video_url"] = None