💡 前言
在日常开发或办公场景中,我们经常需要处理大量的会议录像或访谈视频。如果能将视频自动提取音频 -> 语音转写为文字 -> 提取结构化对话 -> 交由大模型总结,能极大地提升效率。
本文将手把手带你打通这条 AI 流水线,使用 uv 管理环境,结合 ffmpeg、讯飞语音转写(LFASR) 以及 讯飞星火大模型(HTTP 兼容接口) 实现完整落地。文中包含了大量实战中遇到的坑与解决方案,建议收藏!
🛠️ 技术栈与环境准备
-
Python 版本 :3.11(使用
uv极速管理) -
音视频处理 :
ffmpeg(或使用imageio-ffmpeg兜底) -
语音转写:讯飞语音转写 API(长音频)
-
大模型:讯飞星火大模型(OpenAI SDK 兼容协议)
1. 依赖安装
推荐使用 uv 创建虚拟环境(没装的可以用 pip install uv):
bash
uv init --python 3.11
uv venv --python 3.11
uv add requests openai imageio-ffmpeg
🚀 第一步:视频分离音频(封装校验,防报错)
我们需要传入一个视频文件,将其剥离出 16k/单声道的 .wav 音频,这是大多数语音识别 API 最友好的格式。
核心逻辑 :优先调用系统 ffmpeg,如果没有则使用 imageio-ffmpeg 自带的;必须加入文件存在性校验,避免路径错误导致程序崩溃。
python
import os
import subprocess
from pathlib import Path
class VideoAudioExtractor:
def __init__(self, sample_rate=16000, channels=1):
self.sample_rate = sample_rate
self.channels = channels
import imageio_ffmpeg
self.ffmpeg = imageio_ffmpeg.get_ffmpeg_exe() # 简化版,建议优先用 shutil.which("ffmpeg")
def check_video(self, video_path):
p = Path(video_path)
if not p.exists():
print(f"❌ 视频文件不存在: {p.resolve()}")
return False
if p.stat().st_size == 0:
print(f"❌ 视频文件为空: {p.name}")
return False
return True
def extract(self, video_path, output_dir="./outputs"):
if not self.check_video(video_path): return ""
video = Path(video_path)
out_dir = Path(output_dir)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{video.stem}.wav"
cmd = [self.ffmpeg, "-y", "-i", str(video), "-vn",
"-acodec", "pcm_s16le", "-ar", str(self.sample_rate),
"-ac", str(self.channels), str(out_path)]
subprocess.run(cmd, capture_output=True, check=True)
print(f"✅ 音频已分离保存至: {out_path}")
return str(out_path)
🎙️ 第二步:讯飞语音转写(LFASR)获取纯文本
讯飞的长音频转写是通过上传文件 -> 轮询获取结果的方式。
⚠️ 踩坑点 1:duration 参数导致识别为空
原代码里通常写死 param_dict["duration"] = "200"。如果你的音频有几分钟,接口可能只处理前 200 毫秒,导致最终返回的 orderResult 为空 []。建议获取真实音频时长或传一个大值。
python
import time, requests, json, base64, hashlib, hmac, urllib
def upload_and_get_result(appid, secret_key, audio_path):
# 1. 生成签名
ts = str(int(time.time()))
m2 = hashlib.md5((appid + ts).encode('utf-8')).hexdigest()
signa = base64.b64encode(hmac.new(secret_key.encode('utf-8'), m2.encode('utf-8'), hashlib.sha1).digest()).decode('utf-8')
# 2. 上传
param_dict = {
'appId': appid, 'signa': signa, 'ts': ts,
'fileName': os.path.basename(audio_path),
'fileSize': os.path.getsize(audio_path),
'duration': '60000' # 告诉接口音频大概多长,避免空结果
}
with open(audio_path, 'rb') as f:
data = f.read()
resp = requests.post(f"https://raasr.xfyun.cn/v2/api/upload?{urllib.parse.urlencode(param_dict)}",
headers={"Content-type": "application/json"}, data=data).json()
orderId = resp['content']['orderId']
# 3. 轮询获取结果
while True:
query_dict = param_dict.copy()
query_dict.update({'orderId': orderId, 'resultType': 'transfer,predict'})
res = requests.post(f"https://raasr.xfyun.cn/v2/api/getResult?{urllib.parse.urlencode(query_dict)}",
headers={"Content-type": "application/json"}).json()
if res['content']['orderInfo']['status'] == 4:
return res
time.sleep(5)
📦 解析结果:提取时间、角色与对话内容
讯飞返回的 orderResult 是个多层嵌套的 JSON,我们需要将它清洗成标准的对话 JSON。
python
def extract_dialogue_json(result_dict, output_file="dialogue.json"):
order_result = result_dict.get("content", {}).get("orderResult", "")
if not order_result: return []
data = json.loads(order_result)
dialogue_list = []
for segment in data:
if isinstance(segment, str):
try: segment = json.loads(segment)
except: continue
text = segment.get("paragraph_text", "").strip()
if not text: continue
# 毫秒转 MM:SS
start_ms = segment.get("start_ms", 0)
time_str = f"{start_ms // 60000:02d}:{(start_ms % 60000) // 1000:02d}"
# 角色映射
spk_raw = segment.get("spk", "unknown")
role = spk_raw.replace("段落-", "说话人")
dialogue_list.append({"time": time_str, "role": role, "content": text})
with open(output_file, "w", encoding="utf-8") as f:
json.dump(dialogue_list, f, ensure_ascii=False, indent=4)
return dialogue_list
🧠 第三步:接入讯飞星火大模型(OpenAI SDK 兼容)
目前星火提供了兼容 OpenAI 协议的 HTTP 接口,调用非常丝滑。
⚠️ 踩坑点 2:AppIdNoAuthError 报错
很多开发者习惯把星火的 APIKey 和 APISecret 填进 HTTP 接口中,这会直接报 11200 错误!HTTP 接口需要使用控制台里专门提供的 API Password ,并且 base_url 和 model 必须版本对应。
python
from openai import OpenAI
class SparkAnalyzer:
def __init__(self, api_password):
self.client = OpenAI(
api_key=api_password,
base_url="https://spark-api-open.xf-yun.com/v1" # 必须是 v1
)
self.model = "generalv3.5" # 必须与开通的版本匹配,如 lite, generalv3.5, 4.0Ultra
def chat(self, prompt):
try:
response = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}],
stream=False
)
return response.choices[0].message.content
except Exception as e:
return f"调用失败: {e}"
🔗 第四步:整体串联与测试
将以上模块组装起来,你的 main.py 最终长这样:
python
if __name__ == '__main__':
# 1. 视频分离
extractor = VideoAudioExtractor()
wav_path = extractor.extract(r"C:\Users\Videos\demo.mp4")
if wav_path:
# 2. 语音转写
print("正在上传转写...")
asr_res = upload_and_get_result(appid="你的ASR_APPID", secret_key="你的Secret", audio_path=wav_path)
# 3. 提取并保存 JSON
dialogues = extract_dialogue_json(asr_res, "meeting_dialogue.json")
print(f"✅ 成功提取 {len(dialogues)} 句对话!")
# 4. 大模型总结
if dialogues:
full_text = "\n".join([f"[{d['time']}] {d['role']}: {d['content']}" for d in dialogues])
spark = SparkAnalyzer(api_password="你的星火_API_PASSWORD")
print("正在请求大模型总结...")
summary = spark.chat(f"请为以下会议记录写一份摘要,并提取核心待办事项:\n{full_text}")
print("\n==== 星火大模型总结 ====\n", summary)
📝 总结与避坑清单
-
长音频识别为空 :检查讯飞转写上传时的
duration参数,宁可传大点(如"60000")也不要写死"200"。 -
讯飞转写报错
'str' object has no attribute 'get':讯飞返回的 JSON 字段嵌套常常会变,解析时一定要用isinstance(utt, dict)或者尝试json.loads二次解析防崩。 -
星火报错
AppIdNoAuthError:-
切忌混用!WebSocket 使用
APPID+APIKey+APISecret。 -
HTTP(OpenAI SDK)使用
API Password。 -
模型版本:记得检查控制台的免费额度(比如
generalv3.5对应 Spark Max)。
-
-
中文路径与乱码 :Python 中文件读写务必加上
encoding="utf-8"和ensure_ascii=False。
通过这套流水线,你可以轻松把任意视频变成结构化的会议纪要。如果有帮到你,欢迎点赞、收藏、关注三连!有任何问题欢迎在评论区交流。