This commit is contained in:
Ubuntu
2026-07-03 16:58:28 +08:00
commit 32b43f85bd
6240 changed files with 1987678 additions and 0 deletions
+55
View File
@@ -0,0 +1,55 @@
# Image Generation Skill
为nanobot提供图片生成功能。
## 功能
- 生成数据图表(条形图、折线图)
- 生成二维码
- 文本转图片
- 系统状态图
- 信息卡片
## 依赖库
```bash
pip install Pillow matplotlib qrcode numpy --user
```
## 使用方法
### 生成图表
```python
from image_generation import create_chart
data = {
'labels': ['Python', 'JavaScript', 'Java'],
'values': [85, 90, 75]
}
chart_path = create_chart(data, chart_type='bar', title='编程语言流行度')
```
### 生成二维码
```python
from image_generation import create_qrcode
qr_path = create_qrcode('https://github.com/nanobot-ai/nanobot', size=200)
```
### 文本转图片
```python
from image_generation import text_to_image
text_path = text_to_image('Hello nanobot!\\n测试文本', width=400, height=200)
```
## 命令示例
- `生成图表 [数据] [类型] [标题]`
- `生成二维码 [内容] [大小]`
- `文本转图片 [文本]`
## 配置
默认配置已足够使用,如需自定义可创建config.json文件。
## 注意事项
1. 需要安装依赖库
2. 中文字体需要额外安装
3. 生成大图片可能需要更多内存
+398
View File
@@ -0,0 +1,398 @@
"""
图片生成技能 - 完整版本(支持中文)
整合多种图片生成功能
"""
import os
import tempfile
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import seaborn as sns
import qrcode
from wordcloud import WordCloud
# 导入字体工具
try:
# 尝试不同的导入方式
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from font_utils import get_chinese_font, setup_matplotlib_chinese
CHINESE_SUPPORT = True
except ImportError as e:
CHINESE_SUPPORT = False
print(f"⚠️ 字体工具导入失败,中文支持可能受限: {e}")
# 设置matplotlib为非交互模式
plt.switch_backend('Agg')
sns.set_style("whitegrid")
# 尝试设置matplotlib中文支持
if CHINESE_SUPPORT:
setup_matplotlib_chinese()
class ImageGenerationSkill:
"""图片生成技能主类"""
def __init__(self, config=None):
self.config = config or {}
# 尝试使用中文字体
if CHINESE_SUPPORT:
self.default_font = get_chinese_font(14)
else:
self.default_font = ImageFont.load_default()
print("⚠️ 使用默认字体,中文可能显示为方框")
print("Image Generation Skill v2.0 (中文支持) 初始化完成")
# ========== 基础功能 ==========
def create_chart(self, data, chart_type='bar', title='', style='default'):
"""创建图表
Args:
data: 数据字典 {'labels': [], 'values': []}
chart_type: 图表类型 ('bar', 'line', 'pie', 'scatter')
title: 图表标题
style: 样式 ('default', 'seaborn')
Returns:
图片路径
"""
try:
plt.figure(figsize=(10, 6))
if style == 'seaborn':
sns.set_palette("husl")
labels = data.get('labels', [])
values = data.get('values', [])
if chart_type == 'bar':
if style == 'seaborn':
ax = sns.barplot(x=labels, y=values)
# 添加数值标签
for i, v in enumerate(values):
ax.text(i, v + 0.1, str(v), ha='center')
else:
bars = plt.bar(labels, values)
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.1,
f'{height}', ha='center', va='bottom')
elif chart_type == 'line':
if style == 'seaborn':
sns.lineplot(x=labels, y=values, marker='o', linewidth=2)
else:
plt.plot(labels, values, marker='o', linewidth=2)
elif chart_type == 'pie':
plt.pie(values, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal')
elif chart_type == 'scatter' and 'x' in data and 'y' in data:
if style == 'seaborn':
sns.scatterplot(x=data['x'], y=data['y'])
else:
plt.scatter(data['x'], data['y'])
if title:
plt.title(title, fontsize=14, fontweight='bold')
plt.tight_layout()
path = tempfile.mktemp(suffix='.png')
plt.savefig(path, dpi=120, bbox_inches='tight')
plt.close()
return path
except Exception as e:
plt.close()
raise Exception(f'图表生成失败: {e}')
def create_qrcode(self, content, size=200, output_path=None):
"""生成二维码"""
try:
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(content)
qr.make(fit=True)
qr_img = qr.make_image(fill_color='black', back_color='white')
qr_img = qr_img.resize((size, size))
if output_path is None:
output_path = tempfile.mktemp(suffix='.png')
qr_img.save(output_path)
return output_path
except Exception as e:
raise Exception(f'二维码生成失败: {e}')
def text_to_image(self, text, width=400, height=200,
bg_color='white', text_color='black'):
"""文本转图片"""
try:
img = Image.new('RGB', (width, height), color=bg_color)
draw = ImageDraw.Draw(img)
lines = text.split('\n')
line_height = 30
y_start = max(20, (height - len(lines) * line_height) // 2)
for i, line in enumerate(lines):
y = y_start + i * line_height
# 简单居中
text_width = len(line) * 10
x = max(20, (width - text_width) // 2)
draw.text((x, y), line, fill=text_color, font=self.default_font)
path = tempfile.mktemp(suffix='.png')
img.save(path)
return path
except Exception as e:
raise Exception(f'文本转图片失败: {e}')
# ========== 高级功能 ==========
def create_wordcloud(self, text, width=800, height=400,
background_color='white', colormap='viridis'):
"""创建词云图"""
try:
wordcloud = WordCloud(
width=width,
height=height,
background_color=background_color,
colormap=colormap,
max_words=200,
contour_width=1,
contour_color='steelblue'
).generate(text)
path = tempfile.mktemp(suffix='.png')
wordcloud.to_file(path)
return path
except Exception as e:
raise Exception(f'词云图生成失败: {e}')
def create_color_palette(self, colors, title='颜色调色板'):
"""创建颜色调色板"""
try:
fig, axes = plt.subplots(1, len(colors), figsize=(len(colors)*2, 3))
if len(colors) == 1:
axes = [axes]
for ax, color in zip(axes, colors):
ax.add_patch(plt.Rectangle((0, 0), 1, 1, color=color))
ax.text(0.5, -0.2, color, ha='center', transform=ax.transAxes)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.tight_layout()
path = tempfile.mktemp(suffix='.png')
plt.savefig(path, dpi=100, bbox_inches='tight')
plt.close()
return path
except Exception as e:
plt.close()
raise Exception(f'颜色调色板生成失败: {e}')
def create_data_card(self, title, data_dict, theme='light'):
"""创建数据卡片"""
try:
# 设置颜色主题
if theme == 'dark':
bg_color = '#2c3e50'
text_color = '#ecf0f1'
accent_color = '#3498db'
else:
bg_color = '#ffffff'
text_color = '#2c3e50'
accent_color = '#3498db'
# 计算卡片尺寸
num_items = len(data_dict)
card_width = 500
card_height = 150 + num_items * 40
# 创建卡片
img = Image.new('RGB', (card_width, card_height), color=bg_color)
draw = ImageDraw.Draw(img)
# 标题区域
draw.rectangle([0, 0, card_width, 60], fill=accent_color)
draw.text((20, 20), title, fill='white')
# 数据项
y = 80
for key, value in data_dict.items():
draw.text((30, y), f'• {key}:', fill=text_color)
draw.text((200, y), str(value), fill=accent_color)
# 如果是百分比,添加进度条
if isinstance(value, (int, float)) and 0 <= value <= 100:
bar_width = 200
bar_height = 20
bar_x = 250
# 进度条背景
draw.rectangle([bar_x, y, bar_x + bar_width, y + bar_height],
fill='#ecf0f1' if theme == 'light' else '#34495e')
# 进度条前景
fill_width = int(bar_width * value / 100)
draw.rectangle([bar_x, y, bar_x + fill_width, y + bar_height],
fill=accent_color)
# 百分比文本
text_color_bar = 'white' if value > 50 else text_color
draw.text((bar_x + 5, y), f'{value}%', fill=text_color_bar)
y += 40
# 边框
draw.rectangle([10, 70, card_width - 10, card_height - 10],
outline=accent_color, width=2)
path = tempfile.mktemp(suffix='.png')
img.save(path)
return path
except Exception as e:
raise Exception(f'数据卡片生成失败: {e}')
def create_system_status(self, status_data):
"""生成系统状态图"""
try:
width, height = 600, 400
img = Image.new('RGB', (width, height), color='#f8f9fa')
draw = ImageDraw.Draw(img)
# 标题
draw.rectangle([0, 0, width, 60], fill='#2c3e50')
draw.text((20, 20), '🖥️ 系统状态监控', fill='white', font=self.default_font)
items = list(status_data.items())
y_start = 80
for i, (label, value) in enumerate(items):
y = y_start + i * 50
draw.text((40, y), f'• {label}', fill='#34495e', font=self.default_font)
draw.text((200, y), str(value), fill='#3498db', font=self.default_font)
import datetime
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
draw.text((40, height-30), f'生成时间: {timestamp}',
fill='#7f8c8d', font=self.default_font)
path = tempfile.mktemp(suffix='.png')
img.save(path)
return path
except Exception as e:
raise Exception(f'系统状态图生成失败: {e}')
def create_comparison_chart(self, data_sets, labels, chart_type='grouped_bar'):
"""创建对比图表"""
try:
plt.figure(figsize=(12, 7))
x = np.arange(len(labels))
width = 0.8 / len(data_sets)
if chart_type == 'grouped_bar':
for i, data in enumerate(data_sets):
offset = (i - len(data_sets)/2 + 0.5) * width
bars = plt.bar(x + offset, data, width, label=f'数据集 {i+1}')
# 添加数值标签
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.1,
f'{height}', ha='center', va='bottom', fontsize=8)
elif chart_type == 'stacked_bar':
bottom = np.zeros(len(labels))
for i, data in enumerate(data_sets):
plt.bar(x, data, width, bottom=bottom, label=f'数据集 {i+1}')
bottom += data
elif chart_type == 'line':
for i, data in enumerate(data_sets):
plt.plot(x, data, marker='o', linewidth=2, label=f'数据集 {i+1}')
plt.xlabel('类别', fontsize=12)
plt.ylabel('数值', fontsize=12)
plt.title('数据对比分析', fontsize=14, fontweight='bold')
plt.xticks(x, labels)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
path = tempfile.mktemp(suffix='.png')
plt.savefig(path, dpi=120, bbox_inches='tight')
plt.close()
return path
except Exception as e:
plt.close()
raise Exception(f'对比图表生成失败: {e}')
# 创建技能实例
skill = ImageGenerationSkill()
# 快捷函数
def create_chart(*args, **kwargs):
return skill.create_chart(*args, **kwargs)
def create_qrcode(*args, **kwargs):
return skill.create_qrcode(*args, **kwargs)
def text_to_image(*args, **kwargs):
return skill.text_to_image(*args, **kwargs)
def create_wordcloud(*args, **kwargs):
return skill.create_wordcloud(*args, **kwargs)
def create_color_palette(*args, **kwargs):
return skill.create_color_palette(*args, **kwargs)
def create_data_card(*args, **kwargs):
return skill.create_data_card(*args, **kwargs)
def create_system_status(*args, **kwargs):
return skill.create_system_status(*args, **kwargs)
def create_comparison_chart(*args, **kwargs):
return skill.create_comparison_chart(*args, **kwargs)
__all__ = [
'ImageGenerationSkill',
'skill',
'create_chart',
'create_qrcode',
'text_to_image',
'create_wordcloud',
'create_color_palette',
'create_data_card',
'create_system_status',
'create_comparison_chart'
]
+376
View File
@@ -0,0 +1,376 @@
"""
高级图片生成技能 - 整合多个库
"""
import os
import tempfile
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import seaborn as sns
import qrcode
from wordcloud import WordCloud
import ascii_magic
class AdvancedImageSkill:
"""高级图片生成技能"""
def __init__(self):
plt.switch_backend('Agg')
sns.set_style("whitegrid")
self.default_font = ImageFont.load_default()
print("Advanced Image Skill initialized")
def create_advanced_chart(self, data, chart_type='bar', title='', style='seaborn'):
"""创建高级图表
Args:
data: 数据字典
chart_type: 图表类型 ('bar', 'line', 'scatter', 'heatmap', 'pie')
title: 图表标题
style: 样式 ('seaborn', 'matplotlib')
Returns:
图片路径
"""
try:
plt.figure(figsize=(10, 6))
if style == 'seaborn':
sns.set_palette("husl")
labels = data.get('labels', [])
values = data.get('values', [])
if chart_type == 'bar':
if style == 'seaborn':
ax = sns.barplot(x=labels, y=values)
# 添加数值标签
for i, v in enumerate(values):
ax.text(i, v + 0.1, str(v), ha='center')
else:
bars = plt.bar(labels, values)
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.1,
f'{height}', ha='center', va='bottom')
elif chart_type == 'line':
if style == 'seaborn':
sns.lineplot(x=labels, y=values, marker='o', linewidth=2)
else:
plt.plot(labels, values, marker='o', linewidth=2)
elif chart_type == 'scatter' and 'x' in data and 'y' in data:
if style == 'seaborn':
sns.scatterplot(x=data['x'], y=data['y'])
else:
plt.scatter(data['x'], data['y'])
elif chart_type == 'heatmap' and 'matrix' in data:
if style == 'seaborn':
sns.heatmap(data['matrix'], annot=True, fmt='.1f', cmap='YlOrRd')
else:
plt.imshow(data['matrix'], cmap='hot', interpolation='nearest')
plt.colorbar()
elif chart_type == 'pie':
plt.pie(values, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal') # 确保饼图是圆形
if title:
plt.title(title, fontsize=14, fontweight='bold')
plt.tight_layout()
path = tempfile.mktemp(suffix='.png')
plt.savefig(path, dpi=120, bbox_inches='tight')
plt.close()
return path
except Exception as e:
plt.close()
raise Exception(f'高级图表生成失败: {e}')
def create_wordcloud(self, text, width=800, height=400,
background_color='white', colormap='viridis'):
"""创建词云图
Args:
text: 文本内容
width: 图片宽度
height: 图片高度
background_color: 背景颜色
colormap: 颜色映射
Returns:
图片路径
"""
try:
# 创建词云
wordcloud = WordCloud(
width=width,
height=height,
background_color=background_color,
colormap=colormap,
max_words=200,
contour_width=1,
contour_color='steelblue'
).generate(text)
# 保存图片
path = tempfile.mktemp(suffix='.png')
wordcloud.to_file(path)
return path
except Exception as e:
raise Exception(f'词云图生成失败: {e}')
def create_ascii_art(self, image_path=None, text=None, columns=100):
"""创建ASCII艺术
Args:
image_path: 图片路径(将图片转为ASCII)
text: 文本(创建文本ASCII艺术)
columns: 列数
Returns:
ASCII文本或图片路径
"""
try:
if image_path and os.path.exists(image_path):
# 从图片创建ASCII艺术
output = ascii_magic.from_image(
image_path,
columns=columns,
mode=ascii_magic.Modes.HTML
)
# 保存为HTML
path = tempfile.mktemp(suffix='.html')
ascii_magic.to_html_file(path, output)
return path
elif text:
# 从文本创建ASCII艺术
# 这里简化处理,实际可以使用更复杂的ASCII艺术生成
ascii_text = f"""
╔{'═' * (columns-2)}╗
║{' ' * (columns-2)}║
║{text.center(columns-2)}║
║{' ' * (columns-2)}║
╚{'═' * (columns-2)}╝
"""
path = tempfile.mktemp(suffix='.txt')
with open(path, 'w', encoding='utf-8') as f:
f.write(ascii_text)
return path
else:
raise Exception('需要提供图片路径或文本')
except Exception as e:
raise Exception(f'ASCII艺术生成失败: {e}')
def create_color_palette(self, colors, title='颜色调色板'):
"""创建颜色调色板展示
Args:
colors: 颜色列表,如 ['#FF5733', '#33FF57', '#3357FF']
title: 标题
Returns:
图片路径
"""
try:
fig, axes = plt.subplots(1, len(colors), figsize=(len(colors)*2, 3))
if len(colors) == 1:
axes = [axes]
for ax, color in zip(axes, colors):
ax.add_patch(plt.Rectangle((0, 0), 1, 1, color=color))
ax.text(0.5, -0.2, color, ha='center', transform=ax.transAxes)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')
plt.suptitle(title, fontsize=14, fontweight='bold')
plt.tight_layout()
path = tempfile.mktemp(suffix='.png')
plt.savefig(path, dpi=100, bbox_inches='tight')
plt.close()
return path
except Exception as e:
plt.close()
raise Exception(f'颜色调色板生成失败: {e}')
def create_data_card(self, title, data_dict, theme='light'):
"""创建数据卡片
Args:
title: 卡片标题
data_dict: 数据字典
theme: 主题 ('light', 'dark')
Returns:
图片路径
"""
try:
# 设置颜色主题
if theme == 'dark':
bg_color = '#2c3e50'
text_color = '#ecf0f1'
accent_color = '#3498db'
else:
bg_color = '#ffffff'
text_color = '#2c3e50'
accent_color = '#3498db'
# 计算卡片尺寸
num_items = len(data_dict)
card_width = 500
card_height = 150 + num_items * 40
# 创建卡片
img = Image.new('RGB', (card_width, card_height), color=bg_color)
draw = ImageDraw.Draw(img)
# 标题区域
draw.rectangle([0, 0, card_width, 60], fill=accent_color)
draw.text((20, 20), title, fill='white' if theme == 'dark' else 'white')
# 数据项
y = 80
for key, value in data_dict.items():
# 键
draw.text((30, y), f'• {key}:', fill=text_color)
# 值(如果是数字,可以添加进度条)
value_x = 200
draw.text((value_x, y), str(value), fill=accent_color)
# 如果是百分比,添加进度条
if isinstance(value, (int, float)) and 0 <= value <= 100:
bar_width = 200
bar_height = 20
bar_x = 250
# 进度条背景
draw.rectangle([bar_x, y, bar_x + bar_width, y + bar_height],
fill='#ecf0f1' if theme == 'light' else '#34495e')
# 进度条前景
fill_width = int(bar_width * value / 100)
draw.rectangle([bar_x, y, bar_x + fill_width, y + bar_height],
fill=accent_color)
# 百分比文本
draw.text((bar_x + 5, y), f'{value}%',
fill='white' if value > 50 else text_color)
y += 40
# 边框
draw.rectangle([10, 70, card_width - 10, card_height - 10],
outline=accent_color, width=2)
path = tempfile.mktemp(suffix='.png')
img.save(path)
return path
except Exception as e:
raise Exception(f'数据卡片生成失败: {e}')
def create_comparison_chart(self, data_sets, labels, chart_type='grouped_bar'):
"""创建对比图表
Args:
data_sets: 数据集列表,每个数据集是一个数值列表
labels: 标签列表
chart_type: 图表类型 ('grouped_bar', 'stacked_bar', 'line')
Returns:
图片路径
"""
try:
plt.figure(figsize=(12, 7))
x = np.arange(len(labels))
width = 0.8 / len(data_sets)
if chart_type == 'grouped_bar':
for i, data in enumerate(data_sets):
offset = (i - len(data_sets)/2 + 0.5) * width
bars = plt.bar(x + offset, data, width, label=f'数据集 {i+1}')
# 添加数值标签
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height + 0.1,
f'{height}', ha='center', va='bottom', fontsize=8)
elif chart_type == 'stacked_bar':
bottom = np.zeros(len(labels))
for i, data in enumerate(data_sets):
plt.bar(x, data, width, bottom=bottom, label=f'数据集 {i+1}')
bottom += data
elif chart_type == 'line':
for i, data in enumerate(data_sets):
plt.plot(x, data, marker='o', linewidth=2, label=f'数据集 {i+1}')
plt.xlabel('类别', fontsize=12)
plt.ylabel('数值', fontsize=12)
plt.title('数据对比分析', fontsize=14, fontweight='bold')
plt.xticks(x, labels)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
path = tempfile.mktemp(suffix='.png')
plt.savefig(path, dpi=120, bbox_inches='tight')
plt.close()
return path
except Exception as e:
plt.close()
raise Exception(f'对比图表生成失败: {e}')
# 创建技能实例
advanced_skill = AdvancedImageSkill()
# 导出函数
def create_advanced_chart(*args, **kwargs):
return advanced_skill.create_advanced_chart(*args, **kwargs)
def create_wordcloud(*args, **kwargs):
return advanced_skill.create_wordcloud(*args, **kwargs)
def create_ascii_art(*args, **kwargs):
return advanced_skill.create_ascii_art(*args, **kwargs)
def create_color_palette(*args, **kwargs):
return advanced_skill.create_color_palette(*args, **kwargs)
def create_data_card(*args, **kwargs):
return advanced_skill.create_data_card(*args, **kwargs)
def create_comparison_chart(*args, **kwargs):
return advanced_skill.create_comparison_chart(*args, **kwargs)
__all__ = [
'AdvancedImageSkill',
'advanced_skill',
'create_advanced_chart',
'create_wordcloud',
'create_ascii_art',
'create_color_palette',
'create_data_card',
'create_comparison_chart'
]
+83
View File
@@ -0,0 +1,83 @@
"""
字体工具 - 用于处理中文字体
"""
import os
from PIL import ImageFont
def get_chinese_font(font_size=14):
"""获取中文字体
Args:
font_size: 字体大小
Returns:
ImageFont对象
"""
# 中文字体路径列表(按优先级排序)
chinese_fonts = [
# 文泉驿字体
'/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc',
# Noto Sans CJK
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
'/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc',
# 其他可能的中文字体
'/usr/share/fonts/truetype/arphic/uming.ttc',
'/usr/share/fonts/truetype/arphic/ukai.ttc',
]
for font_path in chinese_fonts:
if os.path.exists(font_path):
try:
return ImageFont.truetype(font_path, font_size)
except Exception as e:
print(f'字体加载失败 {font_path}: {e}')
continue
# 如果找不到中文字体,使用默认字体
print('⚠️ 未找到中文字体,使用默认字体')
return ImageFont.load_default()
def setup_matplotlib_chinese():
"""设置matplotlib支持中文显示"""
try:
import matplotlib.pyplot as plt
import matplotlib
# 查找中文字体
font_path = None
for path in [
'/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc',
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc'
]:
if os.path.exists(path):
font_path = path
break
if font_path:
# 添加字体到matplotlib
import matplotlib.font_manager as fm
fm.fontManager.addfont(font_path)
font_name = fm.FontProperties(fname=font_path).get_name()
# 设置中文字体
plt.rcParams['font.sans-serif'] = [font_name]
plt.rcParams['axes.unicode_minus'] = False
print(f'✅ matplotlib已设置中文字体: {font_name}')
return True
else:
print('⚠️ 未找到matplotlib可用的中文字体')
return False
except Exception as e:
print(f'❌ matplotlib中文设置失败: {e}')
return False
# 预加载字体
CHINESE_FONT = get_chinese_font(14)
MATPLOTLIB_CHINESE_SETUP = setup_matplotlib_chinese()
if __name__ == '__main__':
print('字体工具测试:')
print(f'中文字体: {CHINESE_FONT}')
print(f'matplotlib中文支持: {MATPLOTLIB_CHINESE_SETUP}')
+5
View File
@@ -0,0 +1,5 @@
# Image Generation Skill 依赖库
Pillow>=10.0.0
matplotlib>=3.5.0
qrcode>=7.0.0
numpy>=1.20.0
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""
测试图片生成技能
"""
import sys
import os
# 添加当前目录到路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from image_generation import (
create_chart,
create_qrcode,
text_to_image,
create_system_status
)
def test_chart():
print("测试图表生成...")
data = {
'labels': ['Python', 'JavaScript', 'Java', 'C++', 'Go'],
'values': [85, 90, 75, 60, 55]
}
try:
path = create_chart(data, chart_type='bar', title='编程语言流行度')
print(f"✅ 图表生成成功: {path}")
return True
except Exception as e:
print(f"❌ 图表生成失败: {e}")
return False
def test_qrcode():
print("测试二维码生成...")
try:
path = create_qrcode('https://github.com/nanobot-ai/nanobot', size=200)
print(f"✅ 二维码生成成功: {path}")
return True
except Exception as e:
print(f"❌ 二维码生成失败: {e}")
return False
def test_text_image():
print("测试文本转图片...")
try:
path = text_to_image('Hello nanobot!\nImage Generation Test\n2026-03-13')
print(f"✅ 文本转图片成功: {path}")
return True
except Exception as e:
print(f"❌ 文本转图片失败: {e}")
return False
def test_system_status():
print("测试系统状态图...")
status_data = {
'CPU Usage': 42,
'Memory': 68,
'Disk Space': 78,
'Network': 'Online',
'Service': 'Running'
}
try:
path = create_system_status(status_data)
print(f"✅ 系统状态图生成成功: {path}")
return True
except Exception as e:
print(f"❌ 系统状态图生成失败: {e}")
return False
def main():
print("=" * 60)
print("Image Generation Skill 测试")
print("=" * 60)
tests = [
test_chart,
test_qrcode,
test_text_image,
test_system_status
]
results = []
for test in tests:
result = test()
results.append(result)
print()
print("=" * 60)
print("测试结果:")
print("=" * 60)
for i, (test, result) in enumerate(zip(tests, results), 1):
status = "✅ 通过" if result else "❌ 失败"
print(f"{i}. {test.__name__}: {status}")
passed = sum(results)
total = len(results)
print(f"\n总计: {passed}/{total} 个测试通过")
if passed == total:
print("🎉 所有测试通过!技能可以正常使用。")
return 0
else:
print("⚠️ 部分测试失败,请检查问题。")
return 1
if __name__ == '__main__':
sys.exit(main())