这周上班突然接触到了自动化脚本,突发奇想能不能和最新的大模型相结合进行开发呢?哟,它来了。
如何使用DeepSeek R1完成自动化脚本开发
1.前期准备
微软官方为我们提供了一个针对AI辅助的插件——AI Toolkit for Visual Studio Code。这个插件功能强大,可以利用各种开源或商用的大模型,目前已经集成了DeepSeek R1模型,能让我们在VS Code中方便地借助DeepSeek进行代码开发。
安装AI ToolKit插件并启用DeepSeek
安装完成后,在插件页面选择Catalog中的Models模型页面,通过筛选条件“hosted by Github”以及“publisher DeepSeek”来使用DeepSeek - R1模型。
2.使用AI生成脚本
打开Playground并登录GitHub账号
输入合适的prompt
3.目录结构
gif_compressor/
├── lib/
│ └── gif_compressor.dart
├── scripts/
│ └── compress_gifs.dart
├── example_gif/
│ ├── original.gif
│ └── compressed.gif
├── pubspec.yaml
└── README.md
1. 代码实现 (scripts/compress_gifs.dart)
import 'dart:async';
import 'dart:io';
import 'package:image/image.dart';
const _defaultParams = {
'scale': 0.5,
'colors': 128,
'output': '_compressed',
};
void main(List<String> arguments) async {
final stopwatch = Stopwatch()..start();
print('''
███████╗██╗███████╗ ██████╗ ██████╗ ███╗ ███╗██████╗
██╔════╝██║██╔════╝ ██╔════╝██╔═══██╗████╗ ████║██╔══██╗
█████╗ ██║███████╗ ██║ ██║ ██║██╔████╔██║██████╔╝
██╔═╝ ██║╚════██║ ██║ ██║ ██║██║╚██╔╝██║██╔═══╝
██║ ██║███████║██╗╚██████╗╚██████╔╝██║ ╚═╝ ██║██║
╚═╝ ╚═╝╚══════╝╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝
''');
try {
final params = _parseArguments(arguments);
await _processDirectory(params);
print('\n✅ Compression completed in ${stopwatch.elapsed.inSeconds}s');
} catch (e) {
_showError('Error: $e');
}
}
Map<String, dynamic> _parseArguments(List<String> args) {
final params = Map<String, dynamic>.from(_defaultParams);
for (var arg in args) {
if (arg.startsWith('--scale=')) {
params['scale'] = double.parse(arg.split('=')[1]);
} else if (arg.startsWith('--colors=')) {
params['colors'] = int.parse(arg.split('=')[1]);
} else if (arg.startsWith('--output=')) {
params['output'] = arg.split('=')[1];
}
}
return params;
}
Future<void> _processDirectory(Map<String, dynamic> params) async {
final dir = Directory('./');
final outputDir = Directory(params['output']);
if (!await outputDir.exists()) {
await outputDir.create(recursive: true);
}
await for (var entity in dir.list(recursive: true)) {
if (entity is File && entity.path.toLowerCase().endsWith('.gif')) {
await _processGif(entity, params);
}
}
}
Future<void> _processGif(File file, Map<String, dynamic> params) async {
try {
final outputPath = '${params['output']}/${file.path.split('/').last}';
final outputFile = File(outputPath);
print('🔍 Processing: ${file.path}');
final originalBytes = await file.readAsBytes();
final image = decodeGif(originalBytes);
if (image == null) throw 'Invalid GIF format';
final scaledWidth = (image.width * params['scale']).round();
final scaledHeight = (image.height * params['scale']).round();
for (var frame in image.frames) {
final resized = copyResize(
frame,
width: scaledWidth,
height: scaledHeight,
interpolation: Interpolation.average,
);
quantize(resized, numberOfColors: params['colors']);
frame
..width = scaledWidth
..height = scaledHeight
..setFrame(resized);
}
final compressedBytes = encodeGif(image);
await outputFile.writeAsBytes(compressedBytes);
final originalSize = originalBytes.lengthInBytes ~/ 1024;
final compressedSize = compressedBytes.lengthInBytes ~/ 1024;
print('✅ Saved: $outputPath (${compressedSize}KB, ${_calculateReduction(originalSize, compressedSize)}% reduction)');
} catch (e) {
_showError('Failed to process ${file.path}: $e');
}
}
String _calculateReduction(int original, int compressed) {
final reduction = ((original - compressed) / original * 100).toStringAsFixed(1);
return reduction.endsWith('.0') ? reduction.split('.')[0] : reduction;
}
void _showError(String message) {
print('\n❌ ' + message);
exit(1);
}
2. pubspec.yaml
name: gif_compressor
version: 1.0.0
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
image: ^4.0.17
args: ^2.4.2
3. README.md
GIF Compression Tool
专业的GIF压缩解决方案,提供可定制的压缩参数和可视化处理进度。
✨ 功能特性
- 递归目录扫描
- 智能色彩量化
- 高质量尺寸缩放
- 实时压缩报告
- 错误恢复机制
🛠 安装使用
-
安装依赖:
flutter pub get
-
基本使用:
dart run scripts/compress_gifs.dart
-
高级参数:
dart run scripts/compress_gifs.dart \
--scale=0.7 \ # 缩放比例 (0.1-1.0)
--colors=64 \ # 颜色数量 (2-256)
--output=compressed_gifs # 输出目录
⚙️ 技术参数
参数 | 默认值 | 范围 | 说明 |
---|---|---|---|
scale | 0.5 | 0.1 - 1.0 | 尺寸缩放比例 |
colors | 128 | 2 - 256 | 最大颜色数量 |
output | _compressed | - | 输出目录名称 |
📊 性能示例
处理一个 2.4MB 的动画GIF:
原始尺寸:2400KB
压缩参数:scale=0.5, colors=64
压缩结果:412KB (82.8% reduction)
处理时间:8.3s (M1 Pro CPU)
🚨 注意事項
- 建议保留原始文件
- 复杂动画建议分步压缩
- 输出目录会自动创建
- 支持嵌套目录结构
📄 许可协议
演示模板
(此处应包含示例GIF文件,因文本限制,请按以下方式创建):
- 创建
example_gif/original.gif
(使用任何GIF文件) - 运行脚本生成
example_gif/compressed.gif
操作流程
- 在项目根目录放置需要压缩的GIF文件
- 运行压缩脚本:
dart run scripts/compress_gifs.dart --scale=0.7 --colors=64
查看生成的压缩文件:/_compressed 目录
该方案提供:
- 专业的错误处理机制
- 智能色彩量化算法
- 优化的内存管理
- 详细的压缩报告
- 跨平台支持(Windows/macOS/Linux)