需要一个给视频文件重命名的工具,截取视频文件第一帧画面,ocr识别画面内容中的文字,并将文字作为视频名称,并给视频文件重命名,让豆包给指导了一下,但是还是不会弄
# -------------------------- 配置项 --------------------------
$baiduApiKey = "你的百度API Key" # 替换为自己的百度API Key
$baiduSecretKey = "你的百度Secret Key" # 替换为自己的百度Secret Key
$tempImagePath = "$env:TEMP\video_first_frame.png" # 临时截图路径
# -----------------------------------------------------------
# 1. 获取Quicker传入的视频文件路径(Quicker会自动将选中文件路径传入$args[0])
$videoPath = $args[0]
if (-not (Test-Path $videoPath)) {
Write-Error "视频文件不存在:$videoPath"
exit 1
}
# 2. 用FFmpeg截取第一帧
try {
# FFmpeg命令:-i 输入视频 -vframes 1 输出图片 -y 覆盖已有文件
ffmpeg -i "$videoPath" -vframes 1 "$tempImagePath" -y -loglevel quiet
if (-not (Test-Path $tempImagePath)) {
Write-Error "截取视频首帧失败"
exit 1
}
} catch {
Write-Error "FFmpeg执行失败:$_"
exit 1
}
# 3. 调用百度OCR API识别文字
try {
# 3.1 获取百度OCR的Access Token
$tokenUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=$baiduApiKey&client_secret=$baiduSecretKey"
$tokenResponse = Invoke-RestMethod -Uri $tokenUrl -Method Post
$accessToken = $tokenResponse.access_token
# 3.2 转换图片为Base64编码
$imageBytes = [System.IO.File]::ReadAllBytes($tempImagePath)
$imageBase64 = [System.Convert]::ToBase64String($imageBytes)
# 3.3 调用通用文字识别接口
$ocrUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=$accessToken"
$ocrBody = @{
image = $imageBase64
language_type = "CHN_ENG" # 中英混合识别
} | ConvertTo-Json
$ocrResponse = Invoke-RestMethod -Uri $ocrUrl -Method Post -Body $ocrBody -ContentType "application/json"
# 3.4 提取识别的文字(拼接多行)
$ocrText = $ocrResponse.words_result | ForEach-Object { $_.words } | Join-String -Separator ""
if ([string]::IsNullOrEmpty($ocrText)) {
Write-Error "OCR识别结果为空"
exit 1
}
# 清理非法文件名字符
$validFileName = $ocrText -replace '[\\/:*?"<>|]', '_'
} catch {
Write-Error "OCR识别失败:$_"
exit 1
}
# 4. 重命名视频文件(保留原扩展名)
try {
$videoDir = [System.IO.Path]::GetDirectoryName($videoPath)
$videoExt = [System.IO.Path]::GetExtension($videoPath)
$newVideoPath = Join-Path -Path $videoDir -ChildPath "$validFileName$videoExt"
# 避免文件名重复(添加序号)
$i = 1
while (Test-Path $newVideoPath) {
$newVideoPath = Join-Path -Path $videoDir -ChildPath "$validFileName($i)$videoExt"
$i++
}
Rename-Item -Path $videoPath -Destination $newVideoPath -Force
Write-Host "视频重命名成功:`n原路径:$videoPath`n新路径:$newVideoPath"
} catch {
Write-Error "重命名失败:$_"
exit 1
}
# 5. 清理临时截图
if (Test-Path $tempImagePath) {
Remove-Item -Path $tempImagePath -Force
}