mirror of
https://github.com/Zippland/Bubbles.git
synced 2026-02-14 16:26:51 +08:00
persona
This commit is contained in:
@@ -2,10 +2,8 @@
|
||||
|
||||
包含以下功能:
|
||||
- AliyunImage: 阿里云文生图
|
||||
- GeminiImage: 谷歌Gemini文生图
|
||||
"""
|
||||
|
||||
from .img_aliyun_image import AliyunImage
|
||||
from .img_gemini_image import GeminiImage
|
||||
|
||||
__all__ = ['AliyunImage', 'GeminiImage']
|
||||
__all__ = ['AliyunImage']
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
#! /usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
import os
|
||||
import mimetypes
|
||||
import time
|
||||
import random
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
class GeminiImage:
|
||||
"""谷歌AI画图API调用
|
||||
"""
|
||||
|
||||
def __init__(self, config={}) -> None:
|
||||
self.LOG = logging.getLogger("GeminiImage")
|
||||
|
||||
self.enable = config.get("enable", True)
|
||||
self.api_key = config.get("api_key", "") or os.environ.get("GEMINI_API_KEY", "")
|
||||
self.model = config.get("model", "gemini-2.0-flash-exp-image-generation")
|
||||
self.proxy = config.get("proxy", "")
|
||||
|
||||
project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
self.temp_dir = config.get("temp_dir", os.path.join(project_dir, "geminiimg"))
|
||||
|
||||
if not os.path.exists(self.temp_dir):
|
||||
os.makedirs(self.temp_dir)
|
||||
|
||||
if not self.api_key:
|
||||
self.enable = False
|
||||
return
|
||||
|
||||
try:
|
||||
# 设置代理
|
||||
if self.proxy:
|
||||
os.environ["HTTP_PROXY"] = self.proxy
|
||||
os.environ["HTTPS_PROXY"] = self.proxy
|
||||
|
||||
# 初始化客户端
|
||||
self.client = genai.Client(api_key=self.api_key)
|
||||
except Exception:
|
||||
self.enable = False
|
||||
|
||||
def generate_image(self, prompt: str) -> str:
|
||||
"""生成图像并返回图像文件路径
|
||||
"""
|
||||
try:
|
||||
# 设置代理
|
||||
if self.proxy:
|
||||
os.environ["HTTP_PROXY"] = self.proxy
|
||||
os.environ["HTTPS_PROXY"] = self.proxy
|
||||
|
||||
image_prompt = f"生成一张高质量的图片: {prompt}。请直接提供图像,不需要描述。"
|
||||
|
||||
# 发送请求
|
||||
response = self.client.models.generate_content(
|
||||
model=self.model,
|
||||
contents=image_prompt,
|
||||
config=types.GenerateContentConfig(
|
||||
response_modalities=['Text', 'Image']
|
||||
)
|
||||
)
|
||||
|
||||
# 处理响应
|
||||
if hasattr(response, 'candidates') and response.candidates:
|
||||
for candidate in response.candidates:
|
||||
if hasattr(candidate, 'content') and candidate.content:
|
||||
for part in candidate.content.parts:
|
||||
if hasattr(part, 'inline_data') and part.inline_data:
|
||||
# 保存图像
|
||||
file_name = f"gemini_image_{int(time.time())}_{random.randint(1000, 9999)}"
|
||||
file_extension = mimetypes.guess_extension(part.inline_data.mime_type) or ".png"
|
||||
file_path = os.path.join(self.temp_dir, f"{file_name}{file_extension}")
|
||||
|
||||
with open(file_path, "wb") as f:
|
||||
f.write(part.inline_data.data)
|
||||
|
||||
return file_path
|
||||
|
||||
# 如果没有找到图像,尝试获取文本响应
|
||||
try:
|
||||
text_content = response.text
|
||||
if text_content:
|
||||
return f"模型未能生成图像: {text_content[:100]}..."
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
|
||||
return "图像生成失败,可能需要更新模型或调整提示词"
|
||||
|
||||
except Exception as e:
|
||||
error_str = str(e)
|
||||
self.LOG.error(f"图像生成出错: {error_str}")
|
||||
|
||||
# 处理500错误
|
||||
if "500 INTERNAL" in error_str:
|
||||
self.LOG.error("遇到谷歌服务器内部错误")
|
||||
return "谷歌AI服务器临时故障,请稍后再试。这是谷歌服务器的问题,不是你的请求有误。"
|
||||
|
||||
if "timeout" in error_str.lower():
|
||||
return "图像生成超时,请检查网络或代理设置"
|
||||
|
||||
if "violated" in error_str.lower() or "policy" in error_str.lower():
|
||||
return "请求包含违规内容,无法生成图像"
|
||||
|
||||
# 其他常见错误类型处理
|
||||
if "quota" in error_str.lower() or "rate" in error_str.lower():
|
||||
return "API使用配额已用尽或请求频率过高,请稍后再试"
|
||||
|
||||
if "authentication" in error_str.lower() or "auth" in error_str.lower():
|
||||
return "API密钥验证失败,请联系管理员检查配置"
|
||||
|
||||
return f"图像生成失败,错误原因: {error_str.split('.')[-1] if '.' in error_str else error_str}"
|
||||
@@ -5,7 +5,7 @@ import shutil
|
||||
import time
|
||||
from wcferry import Wcf
|
||||
from configuration import Config
|
||||
from image import AliyunImage, GeminiImage
|
||||
from image import AliyunImage
|
||||
|
||||
|
||||
class ImageGenerationManager:
|
||||
@@ -30,22 +30,9 @@ class ImageGenerationManager:
|
||||
|
||||
# 初始化图像生成服务
|
||||
self.aliyun_image = None
|
||||
self.gemini_image = None
|
||||
|
||||
self.LOG.info("开始初始化图像生成服务...")
|
||||
|
||||
# 初始化Gemini图像生成服务
|
||||
try:
|
||||
if hasattr(self.config, 'GEMINI_IMAGE'):
|
||||
self.gemini_image = GeminiImage(self.config.GEMINI_IMAGE)
|
||||
else:
|
||||
self.gemini_image = GeminiImage({})
|
||||
|
||||
if getattr(self.gemini_image, 'enable', False):
|
||||
self.LOG.info("谷歌Gemini图像生成功能已启用")
|
||||
except Exception as e:
|
||||
self.LOG.error(f"初始化谷歌Gemini图像生成服务失败: {e}")
|
||||
|
||||
# 初始化AliyunImage服务
|
||||
if hasattr(self.config, 'ALIYUN_IMAGE') and self.config.ALIYUN_IMAGE.get('enable', False):
|
||||
try:
|
||||
@@ -56,7 +43,7 @@ class ImageGenerationManager:
|
||||
|
||||
def handle_image_generation(self, service_type, prompt, receiver, at_user=None):
|
||||
"""处理图像生成请求的通用函数
|
||||
:param service_type: 服务类型,'aliyun'/'gemini'
|
||||
:param service_type: 服务类型,目前仅支持 'aliyun'
|
||||
:param prompt: 图像生成提示词
|
||||
:param receiver: 接收者ID
|
||||
:param at_user: 被@的用户ID,用于群聊
|
||||
@@ -78,13 +65,6 @@ class ImageGenerationManager:
|
||||
wait_message = "当前模型为阿里V1模型,生成速度非常慢,可能需要等待较长时间,请耐心等候..."
|
||||
else:
|
||||
wait_message = "正在生成图像,请稍等..."
|
||||
elif service_type == 'gemini':
|
||||
if not self.gemini_image or not getattr(self.gemini_image, 'enable', False):
|
||||
self.send_text("谷歌文生图服务未启用", receiver, at_user)
|
||||
return True
|
||||
|
||||
service = self.gemini_image
|
||||
wait_message = "正在通过谷歌AI生成图像,请稍等..."
|
||||
else:
|
||||
self.LOG.error(f"未知的图像生成服务类型: {service_type}")
|
||||
return False
|
||||
@@ -98,7 +78,7 @@ class ImageGenerationManager:
|
||||
try:
|
||||
self.LOG.info(f"开始处理图片: {image_url}")
|
||||
# 谷歌API直接返回本地文件路径,无需下载
|
||||
image_path = image_url if service_type == 'gemini' else service.download_image(image_url)
|
||||
image_path = service.download_image(image_url)
|
||||
|
||||
if image_path:
|
||||
# 创建一个临时副本,避免文件占用问题
|
||||
@@ -167,4 +147,4 @@ class ImageGenerationManager:
|
||||
else:
|
||||
self.LOG.error(f"无法删除文件 {file_path} 经过 {max_retries} 次尝试: {str(e)}")
|
||||
|
||||
return False
|
||||
return False
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
|
||||
阿里云AI绘画:[JiQingzhe2004 (JiQingzhe)](https://github.com/JiQingzhe2004)
|
||||
|
||||
谷歌AI绘画:[JiQingzhe2004 (JiQingzhe)](https://github.com/JiQingzhe2004)
|
||||
|
||||
------
|
||||
|
||||
在`config.yaml`中进行以下配置才可以调用:
|
||||
@@ -25,23 +23,8 @@ aliyun_image: # -----如果要使用阿里云文生图,取消下面的注释
|
||||
trigger_keyword: 牛阿里 # 触发词,默认为"牛阿里"
|
||||
fallback_to_chat: true # 当未启用绘画功能时:true=将请求发给聊天模型处理,false=回复固定的未启用提示信息
|
||||
|
||||
gemini_image: # -----谷歌AI画图配置这行不填-----
|
||||
enable: true # 是否启用谷歌AI画图功能
|
||||
api_key: your-api-key-here # 谷歌Gemini API密钥,必填
|
||||
model: gemini-2.0-flash-exp-image-generation # 模型名称,建议保持默认,只有这一个模型可以进行绘画
|
||||
temp_dir: ./geminiimg # 图片保存目录,可选
|
||||
trigger_keyword: 牛谷歌 # 触发词,默认为"牛谷歌"
|
||||
fallback_to_chat: false # 当未启用绘画功能时:true=将请求发给聊天模型处理,false=回复固定的未启用提示信息
|
||||
```
|
||||
|
||||
## 如何获取API密钥
|
||||
|
||||
1. 访问 [Google AI Studio](https://aistudio.google.com/)
|
||||
2. 创建一个账号或登录
|
||||
3. 访问 [API Keys](https://aistudio.google.com/app/apikeys) 页面
|
||||
4. 创建一个新的API密钥
|
||||
5. 复制API密钥并填入配置文件
|
||||
|
||||
## 使用方法
|
||||
|
||||
直接发送消息或在群聊中@机器人,使用触发词加提示词,例如:
|
||||
@@ -50,7 +33,6 @@ gemini_image: # -----谷歌AI画图配置这行不填-----
|
||||
```
|
||||
牛智谱 一只可爱的猫咪在阳光下玩耍
|
||||
牛阿里 一只可爱的猫咪在阳光下玩耍
|
||||
牛谷歌 一只可爱的猫咪在阳光下玩耍
|
||||
```
|
||||
## 群组的使用方法
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user