From 95c0f1779a765f5430ba3f045d97b514b037ab7d Mon Sep 17 00:00:00 2001
From: Xinfan Chen <2024111082@stu.hit.edu.cn>
Date: Tue, 28 Apr 2026 09:29:59 +0800
Subject: [PATCH] add new video model: happyhorse
---
aigc-director/aigc-claw/backend/tool/image_processor.py | 627 +++++++++++++++++++++++++++++++++++---------------------
1 files changed, 395 insertions(+), 232 deletions(-)
diff --git a/aigc-director/aigc-claw/backend/tool/image_processor.py b/aigc-director/aigc-claw/backend/tool/image_processor.py
index 43571b1..0292e2e 100644
--- a/aigc-director/aigc-claw/backend/tool/image_processor.py
+++ b/aigc-director/aigc-claw/backend/tool/image_processor.py
@@ -1,250 +1,413 @@
-<p align="center">
- <img src="aigc-director-pics/banner.png" width="100%" />
-</p>
+import os
+import requests
+import numpy as np
+from pathlib import Path
+from datetime import datetime, timedelta
+from PIL import Image
+import logging
-<h2 align="center">
- AIGC-Claw: AI 创意视频生成员工
-</h2>
-<h4 align="center">
- <img src="https://img.shields.io/badge/Version-1.0.0-blue.svg" alt="Version">
- <a href="https://github.com/HITsz-TMG/AIGC-Claw/blob/main/LICENSE">
- <img src="https://img.shields.io/github/license/HITsz-TMG/AIGC-Claw?style=flat-square" alt="License">
- </a>
- <a href="https://github.com/HITsz-TMG/AIGC-Claw/stargazers">
- <img src="https://img.shields.io/github/stars/HITsz-TMG/AIGC-Claw?style=flat-square&logo=github" alt="Stars">
- </a>
- <a href="https://github.com/HITsz-TMG/AIGC-Claw/fork">
- <img src="https://img.shields.io/github/forks/HITsz-TMG/AIGC-Claw?style=flat-square&logo=github" alt="Forks">
- </a>
- <img src="https://img.shields.io/badge/Python-3.9+-purple.svg" alt="Python">
- <a href="#openclaw-integration">
- <img src="https://img.shields.io/badge/OpenClaw-Compatible-ff4444?logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZD0iTTEyIDJDNi40OCAyIDIgNi40OCAyIDEyczQuNDggMTAgMTAgMTAgMTAtNC40OCAxMC0xMFMxNy41MiAyIDEyIDJ6IiBmaWxsPSJ3aGl0ZSIvPjwvc3ZnPg==" alt="OpenClaw Compatible">
- </a>
-</h4>
+class ImageProcessor:
+ """
+ 图片处理和上传集合类
+ 支持:图片处理、分割、拼接,以及上传到阿里云OSS
+ """
+
+ # 阿里云DashScope上传配置
+ UPLOAD_API_URL = "https://dashscope.aliyuncs.com/api/v1/uploads"
+
+ def __init__(self,
+ image_path='',
+ api_key: str = "sk-bcab316d69a7414faa9dc29737019333",
+ model_name: str = "wan2.6-i2v-flash"):
+ """
+ 初始化图片处理器
+
+ Args:
+ image_path: 图片文件路径(可选,用于处理已有图片)
+ api_key: DashScope API Key(用于上传,可从环境变量 DASHSCOPE_API_KEY 读取)
+ model_name: 模型名称,默认使用 wan2.6-i2v-flash
+ """
+ # 图片处理部分
+ if image_path != '':
+ self.image_path = image_path
+ self.image = Image.open(image_path)
+ self.image_np = np.array(self.image)
+ self.width, self.height = self.image_np.shape[1], self.image_np.shape[0]
+ else:
+ self.image_path = None
+ self.image = None
+ self.image_np = None
+ self.width = None
+ self.height = None
+
+ # 上传功能部分
+ self.api_key = api_key or os.getenv("DASHSCOPE_API_KEY")
+ self.model_name = model_name
-<p align="center">
- <b><i><font size="5">直接与 <a href="https://github.com/openclaw/openclaw">OpenClaw</a> 对话:"生成 X 的视频" → 搞定。</font></i></b>
-</p>
+ @staticmethod
+ def check_column_white(column_pixels):
+ """检查列是否几乎全白"""
+ is_almost_white = np.logical_or(column_pixels == 254, column_pixels == 255)
+ white_pixels_ratio = np.mean(np.all(is_almost_white, axis=-1))
+ return white_pixels_ratio >= 0.98 # 至少98%的像素为白色
-<div align="center">
+ def find_white_section(self, start, end):
+ """查找指定范围内的白色区间"""
+ white_sections = []
+ in_white_section = False
+ start_index = 0
-🌐 [**English README**](./README_EN.md) 📺 [**Bilibili**](https://space.bilibili.com/2031891503?spm_id_from=333.1007.0.0) ▶️ [**YouTube**](https://www.youtube.com/@imryanxu) 📖 [**集成指南**](https://github.com/HITsz-TMG/AIGC-Claw?tab=readme-ov-file#%E6%96%B9%E5%BC%8F%E4%BA%8Copenclaw-%E8%87%AA%E5%8A%A8%E9%85%8D%E7%BD%AE) 🦀 [**ClawHub**](https://clawhub.ai/hit-cxf/aigc-director)
+ for col in range(start, end):
+ column_pixels = self.image_np[:, col, :]
+ if self.check_column_white(column_pixels):
+ if not in_white_section:
+ start_index = col
+ in_white_section = True
+ else:
+ if in_white_section:
+ white_sections.append((start_index, col))
+ in_white_section = False
-<a href="https://trendshift.io/repositories/24295" target="_blank"><img src="https://trendshift.io/api/badge/repositories/24295" alt="HITsz-TMG%2FAIGC-Claw | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
+ if in_white_section:
+ white_sections.append((start_index, end))
-</div>
+ return white_sections
+ def split_image(self):
+ """将图片从中间分割为左右两部分"""
+ start_col = self.width * 2 // 5
+ end_col = self.width * 3 // 5
+ white_sections = self.find_white_section(start_col, end_col)
-## 💥 News
+ if white_sections:
+ middle_section = white_sections[len(white_sections) // 2]
+ mid_col = (middle_section[0] + middle_section[1]) // 2
+ else:
+ raise ValueError("No suitable white column found within the specified range")
-- `2026/3/27`: 🎬 AIGC-Claw 正式发布,支持从想法到视频生成全流程自动化,用户可随时介入调整。
-- `2026/4/6`: 🎭 AIGC-Claw 推出第二版,针对短剧进行优化。
-- `2026/4/9`: ♾️ AIGC-Claw 推出第三版,新增无限续写,剧情可自定义。
+ left_box = (0, 0, mid_col, self.height)
+ right_box = (mid_col, 0, self.width, self.height)
+ left_image = self.image.crop(left_box)
+ right_image = self.image.crop(right_box)
+ save_dir, filename = os.path.split(self.image_path)
+ base, extension = os.path.splitext(filename)
-## 📖 项目介绍
+ left_image_path = os.path.join(save_dir, base + '_front' + extension)
+ right_image_path = os.path.join(save_dir, base + '_back' + extension)
+ left_image.save(left_image_path)
+ right_image.save(right_image_path)
-AIGC-Claw 是一个面向创意视频生产的 AI 导演系统。**你只需要给出一句想法、一个故事梗概,甚至一个模糊概念,系统就会把它拆解为可执行的影视工作流,持续产出可查看、可确认、可修改、可交付的中间资产,最终生成完整成片**。
+ return left_image_path, right_image_path
+
+ def stitch_images(self, image_paths, output_path):
+ """拼接多张图片"""
+ if not image_paths:
+ raise ValueError("No image paths provided")
+ sample_image = Image.open(image_paths[0])
+ single_width, single_height = sample_image.size
+ num_images = len(image_paths)
+ total_desired_width = single_width
+ total_current_width = single_width * num_images
+ total_width_to_cut = max(0, total_current_width - total_desired_width)
+ width_to_cut_per_image = total_width_to_cut // num_images
+ stitched_image = Image.new('RGB', (total_desired_width, single_height), "white")
+ current_x = 0
+
+ for path in image_paths:
+ image = Image.open(path)
+ if width_to_cut_per_image > 0:
+ left_margin = width_to_cut_per_image // 2
+ right_margin = image.width - width_to_cut_per_image + left_margin
+ image = image.crop((left_margin, 0, right_margin, image.height))
+ stitched_image.paste(image, (current_x, 0))
+ current_x += image.width
+
+ output_dir = os.path.dirname(output_path)
+ if not os.path.exists(output_dir):
+ os.makedirs(output_dir)
+ stitched_image.save(output_path)
+ return output_path
+
+ def download_image(self, image_url, save_path, max_retries=3):
+ """
+ 下载图片,带有重试机制和SSL错误处理
+
+ Args:
+ image_url: 图片URL
+ save_path: 本地保存路径
+ max_retries: 最大重试次数
+ """
+ import time
+ import urllib3
+
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
+
+ for attempt in range(max_retries):
+ try:
+ response = requests.get(
+ image_url,
+ timeout=(10, 30),
+ stream=True,
+ verify=True,
+ headers={
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
+ }
+ )
+
+ if response.status_code == 200:
+ with open(save_path, 'wb') as file:
+ for chunk in response.iter_content(chunk_size=8192):
+ if chunk:
+ file.write(chunk)
+ print(f"✓ 图片下载成功: {save_path}")
+ return True
+ else:
+ print(f"下载失败,状态码: {response.status_code}")
+
+ except requests.exceptions.SSLError as e:
+ print(f"SSL错误 (尝试 {attempt + 1}/{max_retries}): {str(e)[:100]}")
+ if attempt < max_retries - 1:
+ wait_time = (attempt + 1) * 2
+ print(f"等待 {wait_time} 秒后重试...")
+ time.sleep(wait_time)
+ else:
+ print("尝试禁用SSL验证重新下载...")
+ try:
+ response = requests.get(
+ image_url,
+ timeout=(10, 30),
+ stream=True,
+ verify=False,
+ headers={
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
+ }
+ )
+ if response.status_code == 200:
+ with open(save_path, 'wb') as file:
+ for chunk in response.iter_content(chunk_size=8192):
+ if chunk:
+ file.write(chunk)
+ print(f"✓ 图片下载成功(已禁用SSL验证): {save_path}")
+ return True
+ except Exception as fallback_error:
+ print(f"禁用SSL验证后仍然失败: {fallback_error}")
+ raise
+
+ except requests.exceptions.Timeout as e:
+ print(f"超时错误 (尝试 {attempt + 1}/{max_retries}): {e}")
+ if attempt < max_retries - 1:
+ time.sleep((attempt + 1) * 2)
+ else:
+ raise
+
+ except Exception as e:
+ print(f"下载错误 (尝试 {attempt + 1}/{max_retries}): {e}")
+ if attempt < max_retries - 1:
+ time.sleep((attempt + 1) * 2)
+ else:
+ raise
+
+ return False
-它不是单点式的文生视频工具,而是一条覆盖 **剧本策划 → 角色/场景设计 → 分镜规划 → 参考图生成 → 视频生成 → 后期剪辑** 的全流程生产线。相比只给你一个黑盒结果的闭源视频生成框架,AIGC-Claw是一个真正可协作的 AI 导演团队:前一阶段决定后一阶段,所有关键节点都能可视化、可编辑、可继续生成。
+ def resize_image(self, image_path):
+ """调整图片大小(添加顶部空白)"""
+ original_image = Image.open(image_path)
+ width, height = original_image.size
+ top_blank_height = height // 2
+ final_height = height + top_blank_height
+ final_width = int(final_height * 5 / 3)
+ new_image = Image.new("RGB", (final_width, final_height), color="white")
+ left = (final_width - width) // 2
+ top = top_blank_height
+ new_image.paste(original_image, (left, top))
+ new_image.save(image_path)
+ return image_path
+ def has_black_borders(self, image_path, threshold=10, black_limit=20):
+ """检查图片是否有黑色边框"""
+ img = Image.open(image_path)
+ pixels = img.load()
+ width, height = img.size
+
+ def is_black_pixel(pixel):
+ return all(x <= black_limit for x in pixel)
+
+ # 检查顶部和底部边框
+ for y in range(threshold):
+ if all(is_black_pixel(pixels[x, y]) for x in range(width)):
+ return True
+ if all(is_black_pixel(pixels[x, height - 1 - y]) for x in range(width)):
+ return True
+
+ # 检查左右边框
+ for x in range(threshold):
+ if all(is_black_pixel(pixels[x, y]) for y in range(height)):
+ return True
+ if all(is_black_pixel(pixels[width - 1 - x, y]) for y in range(height)):
+ return True
+
+ return False
-
-## 📺 AIGC-Claw 示例(全流程自动化)
-
-<table>
-<tr>
-<td align="center" width="33%">
- <video src="https://github.com/user-attachments/assets/63c2f33c-da50-44f0-8c26-a65611479d6a" controls width="100%"></video>
-</td>
-<td align="center" width="33%">
- <video src="https://github.com/user-attachments/assets/d7c65cad-05b9-46c8-ab0e-96e39909f978" controls width="100%"></video>
-</td>
-<td align="center" width="33%">
- <video src="https://github.com/user-attachments/assets/ec67546e-2d3d-4b34-b1ad-7d860a9bc1aa" controls width="100%"></video>
-</td>
-</tr>
-</table>
-
-<details>
-<summary><b>Web 前端界面</b></summary>
-<div align="center">
-
-| | |
-|:---:|:---:|
-|  |  |
-|  |  |
-|  |  |
-
-</div>
-</details>
-
-<details>
-<summary><b>微信交互</b></summary>
-<div align="center">
-
-| | | | |
-|:---:|:---:|:---:|:---:|
-|  |  |  |  |
-
-</div>
-</details>
-
-<details>
-<summary><b>飞书交互</b></summary>
-<div align="center">
-
-| | | | |
-|:---:|:---:|:---:|:---:|
-|  |  |  |  |
-
-</div>
-</details>
-
-## ✨ 功能特性
-
-| 能力 | 说明 |
-|---|---|
-| 🎬 **从创意到成片的全流程生成** | 一条链路打通剧本、角色、分镜、参考图、视频片段与后期剪辑,把零散生成能力升级为完整视频生产工作流。 |
-| 🖼️ **分镜驱动的可控创作** | 通过结构化剧本、分镜规划与参考图生成,让角色一致性、镜头表达和画面风格更稳定、更可控。 |
-| ✍️ **可修改、可续写、可继续生成** | 支持剧情 / 分镜智能续写,也支持角色、参考图、视频阶段修改后重新生成,避免每次都从头开始。 |
-| 📲 **本地部署、多端协作、产物留存** | 支持 Web 界面、微信 / 飞书协作、OpenClaw Skill 集成,并对剧本、图片、视频片段和最终成片进行全链路留存。 |
-
----
-
-## 🚀 快速开始
-
-### 方式一:手动安装
-
-```bash
-# 1. 克隆项目
-git clone https://github.com/HITsz-TMG/AIGC-Claw.git
-cd AIGC-Claw
-
-# 2. 配置并启动后端
-cd aigc-director/aigc-claw/backend
-
-# 创建虚拟环境并安装依赖
-python -m venv venv
-source venv/bin/activate # Linux/Mac
-pip install -r requirements.txt
-
-# 配置环境变量
-cp .env.example .env
-# 编辑 .env 填入 API Key
-
-# 启动后端
-python api_server.py
-# 服务运行在 http://localhost:8000
-```
-
-```bash
-# 3. 配置并启动前端(新终端)
-cd aigc-director/aigc-claw/frontend
-npm install
-npm run build
-npm start
-# 访问 http://localhost:3000
-```
-
-### 方式二:OpenClaw 自动配置
-
-向 OpenClaw 发送消息:
-
-```
-帮我克隆git仓库:https://github.com/HITsz-TMG/AIGC-Claw.git
-然后把AIGC-Claw中的aigc-director文件夹递归复制到.openclaw/workspace/skills目录下,用作AIGC相关的skill
-```
-
-使用时建议指明 "使用 aigc-director":
-
-```
-用aigc-director来生成一个视频,内容是"一条狗的使命"
-```
-
-### 方式三:通过 ClawHub 安装
-
-请确保本地安装了clawhub-cli
-
-打开终端,输入命令,所有询问均选择yes
-
-```bash
-clawhub install aigc-director
-```
-
-安装完成后,ClawHub 会将 `aigc-director` 复制到 `workspace/skills`(或指定的 skills 目录)。
-
-之后可以参考方式一手动安装自行构建项目并运行,也可以使用OpenClaw完成后续项目构建。
-
-在第一次使用 `aigc-director` 时,如果没有手动构建项目,OpenClaw会自动构建前后端并运行,无需手动初始化(构建项目需要配置环境和编译,请耐心等待)。
-
-
----
-
-## 🔧 配置说明
-
-<details>
-<summary><b>点击展开完整环境要求和变量</b></summary>
-
-### 环境要求
-
-- **Python**: 3.9+
-- **Node.js**: 18+
-- **npm**: 9+
-
-### 后端环境变量
-
-在 `aigc-claw/backend/.env` 中配置:
-
-```bash
-# LLM 配置
-LLM_MODEL=qwen3.5-plus
-VLM_MODEL=qwen-vl-plus
-
-# 图像生成
-IMAGE_T2I_MODEL=doubao-seedream-5-0-260128
-IMAGE_IT2I_MODEL=doubao-seedream-5-0-260128
-
-# 视频生成
-
-VIDEO_MODEL=wan2.7-i2v
-VIDEO_RATIO=16:9
-
-# API Keys
-DASHSCOPE_API_KEY=your_key
-ARK_API_KEY=your_key
-DEEPSEEK_API_KEY=your_key
-```
-
-### 可用模型
-
-| 类型 | 模型 |
-|:---:|:---|
-| **LLM** | qwen3.5-plus, deepseek-chat, gpt-4o, gemini-2.5-flash |
-| **VLM** | qwen-vl-plus, gemini-2.5-flash-image |
-| **文生图** | doubao-seedream-5-0, jimeng_t2i_v40, wan2.6-t2i |
-| **图生图** | doubao-seedream-5-0, jimeng_t2i_v40, wan2.6-image |
-| **视频生成** | doubao-seedance-2-0-260128, wan2.7-i2v, wan2.6-i2v-flash, kling-v3 |
-
-</details>
-
-
-## 🙏 致谢
-
-AIGC-Claw 的想法和设计受到了 [AutoResearchClaw](https://github.com/aiming-lab/AutoResearchClaw)、[huobao-drama](https://github.com/chatfire-AI/huobao-drama)、[LibTV](https://www.liblib.tv/) 与 [libtv-skills](https://github.com/libtv-labs/libtv-skills) 的启发。
-
-
-
-## 📚 系列工作
-
-| 框架图 | 论文信息 |
-|:---:|---|
-| <img src="https://github.com/HITsz-TMG/FilmAgent/blob/main/pics/framework.png?raw=true" width="420" alt="FilmAgent framework"/> | **[SIGGRAPH Asia 2024] FilmAgent: Automating Virtual Film Production Through a Multi-Agent Collaborative Framework**<br>*Zhenran Xu, Jifang Wang, Longyue Wang, Zhouyi Li, Senbao Shi, Baotian Hu, Min Zhang*<br>[[Paper](https://doi.org/10.1145/3681758.3698014)] [[GitHub](https://github.com/HITsz-TMG/AIGC-Claw/blob/main/FilmAgent.md)] |
-| <img src="https://github.com/HITsz-TMG/Anim-Director/blob/main/Anim-Director/assets/visualeg.png" width="420" alt="Anim-Director result"/> | **[SIGGRAPH Asia 2024] Anim-Director: A Large Multimodal Model Powered Agent for Controllable Animation Video Generation**<br>*Yunxin Li, Haoyuan Shi, Baotian Hu, Longyue Wang, Jiashun Zhu, Jinyi Xu, Zhen Zhao, Min Zhang*<br>[[Paper](https://doi.org/10.1145/3680528.3687688)] [[GitHub](https://github.com/HITsz-TMG/Anim-Director/tree/main/Anim-Director)] |
-| <img src="https://raw.githubusercontent.com/HITsz-TMG/Anim-Director/main/AniMaker/assets/pipeline.png" width="420" alt="AniMaker pipeline"/> | **[SIGGRAPH Asia 2025] AniMaker: Multi-Agent Animated Storytelling with MCTS-Driven Clip Generation**<br>*Haoyuan Shi, Yunxin Li, Xinyu Chen, Longyue Wang, Baotian Hu, Min Zhang*<br>[[Paper](https://doi.org/10.1145/3757377.3764009)] [[GitHub](https://github.com/HITsz-TMG/Anim-Director/tree/main/AniMaker)] |
+ # ===== 图片上传功能 =====
+
+ def get_upload_policy(self):
+ """
+ 获取文件上传凭证
+
+ Returns:
+ policy_data: 包含上传所需凭证的字典
+
+ Raises:
+ Exception: 获取上传凭证失败时
+ """
+ if not self.api_key:
+ raise RuntimeError("DASHSCOPE_API_KEY 未设置,无法使用图片上传服务")
+
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json"
+ }
+ params = {
+ "action": "getPolicy",
+ "model": self.model_name
+ }
+
+ response = requests.get(self.UPLOAD_API_URL, headers=headers, params=params)
+ if response.status_code != 200:
+ raise Exception(f"Failed to get upload policy: {response.text}")
+
+ return response.json()['data']
+
+ def upload_file_to_oss(self, policy_data: dict, file_path: str) -> str:
+ """
+ 将文件上传到临时存储OSS
+
+ Args:
+ policy_data: 上传凭证数据
+ file_path: 本地文件路径
+
+ Returns:
+ oss_url: OSS URL (格式: oss://...)
+
+ Raises:
+ Exception: 上传失败时
+ """
+ file_name = Path(file_path).name
+ # Sanitize filename for upload to avoid issues with spaces/characters
+ safe_file_name = "".join([c if c.isalnum() or c in ('-','_','.') else '_' for c in file_name])
+
+ key = f"{policy_data['upload_dir']}/{safe_file_name}"
+
+ with open(file_path, 'rb') as file:
+ files = {
+ 'OSSAccessKeyId': (None, policy_data['oss_access_key_id']),
+ 'Signature': (None, policy_data['signature']),
+ 'policy': (None, policy_data['policy']),
+ 'x-oss-object-acl': (None, policy_data['x_oss_object_acl']),
+ 'x-oss-forbid-overwrite': (None, policy_data['x_oss_forbid_overwrite']),
+ 'key': (None, key),
+ 'success_action_status': (None, '200'),
+ 'file': (safe_file_name, file)
+ }
+
+ response = requests.post(policy_data['upload_host'], files=files)
+ if response.status_code != 200:
+ raise Exception(f"Failed to upload file: {response.text}")
+
+ # Construct OSS URL correctly: oss://<bucket>/<key>
+ # Extract bucket from upload_host (e.g., https://dashscope-instant.oss-cn-beijing.aliyuncs.com)
+ upload_host = policy_data['upload_host']
+ bucket_name = ""
+ if '://' in upload_host:
+ domain = upload_host.split('://')[1]
+ bucket_name = domain.split('.')[0]
+
+ if bucket_name:
+ return f"oss://{bucket_name}/{key}"
+ else:
+ # Fallback if parsing fails (though unlikely for standard OSS hosts)
+ # If the original code's assumption that key was self-sufficient was somehow valid, logic is here.
+ # But normally, oss://<key> is wrong if key doesn't have bucket.
+ return f"oss://{key}"
+
+ def upload(self, file_path: str) -> str:
+ """
+ 上传文件到阿里云OSS并获取URL(统一接口方法)
+
+ Args:
+ file_path: 本地文件路径
+
+ Returns:
+ oss_url: OSS URL,可在48小时内使用
+
+ Raises:
+ FileNotFoundError: 文件不存在时
+ RuntimeError: API Key未设置时
+ Exception: 上传失败时
+ """
+ # 检查文件是否存在
+ if not os.path.exists(file_path):
+ raise FileNotFoundError(f"文件不存在: {file_path}")
+
+ if not self.api_key:
+ raise RuntimeError("DASHSCOPE_API_KEY 未设置,无法使用图片上传服务")
+
+ # 1. 获取上传凭证(注意:上传凭证接口有限流)
+ policy_data = self.get_upload_policy()
+
+ # 2. 上传文件到OSS
+ oss_url = self.upload_file_to_oss(policy_data, file_path)
+
+ # 3. 计算过期时间
+ expire_time = datetime.now() + timedelta(hours=48)
+
+ logging.info(f"文件上传成功: {file_path}")
+ logging.info(f" OSS URL: {oss_url}")
+ logging.info(f" 过期时间: {expire_time.strftime('%Y-%m-%d %H:%M:%S')} (48小时)")
+
+ return oss_url
+ def collage_images(self, image_paths, output_path):
+ """
+ 拼图功能:将多张图片水平拼接
+ Args:
+ image_paths: 图片路径列表
+ output_path: 输出文件路径
+ """
+ if not image_paths:
+ return None
+
+ images = []
+ for p in image_paths:
+ try:
+ img = Image.open(p)
+ images.append(img)
+ except Exception as e:
+ logging.error(f"Cannot open image {p}: {e}")
+
+ if not images:
+ return None
-<p align="center">
- <sub>Built with 🦞 by the Lychee Agent team</sub>
-</p>
+ # 统一高度,按第一张图片的高度调整其他图片
+ base_height = images[0].height
+ resized_images = []
+ for img in images:
+ if img.height != base_height:
+ ratio = base_height / img.height
+ new_width = int(img.width * ratio)
+ resized_images.append(img.resize((new_width, base_height)))
+ else:
+ resized_images.append(img)
+
+ total_width = sum(img.width for img in resized_images)
+ new_im = Image.new('RGB', (total_width, base_height))
+
+ x_offset = 0
+ for img in resized_images:
+ new_im.paste(img, (x_offset, 0))
+ x_offset += img.width
+
+ new_im.save(output_path)
+ return output_path
--
Gitblit v1.8.0