蓝色天空.知识 · 实践 · 创造
我的收藏
AI Agent(智能体) 教程目录 48章
课程介绍
AI Agent(智能体) / LEARN BY DOING

用 Python 核对多模态输入、语音和视频

实际解码 PNG、语音 WAV 和视频帧,核对识别失败、混合输入和时间对齐。

学完这一章,你能够

  • 实际解码 PNG、语音 WAV 和视频帧,核对识别失败、混合输入和时间对齐。

把不同输入保留为可核对的证据

文本适合任务说明与结构化字段,静态图像保存视觉布局,语音和环境音以采样时间为序。视频带有画面、时间轴,也可能有音轨和字幕。文档可混合文字、表格与图片,提取时应保留页码、区域或时间位置。

处理文本任务时保留指令和对话上下文。处理图片时先确定输入格式、尺寸和允许的来源,再选描述、视觉问答、图表读取或界面定位。混合输入应分别保存图片测量和文本要求,以便复核回答依据。执行工具前还需要单独检查允许的动作与确认条件。

用实际像素和请求体核对图像输入

本站 PNG 练习按明确柱中心读取实际像素,得到三个柱高 24、48、72。给出严格大于 48 的文本条件时只选第三柱,改图后选第二和第三柱。这个方法依赖固定图形布局,任意图表还要核对坐标、标签、单位与趋势。

本站文档图将标题和表格划为两个区域,验证像素和边界。它不执行 OCR 或 PDF 文字提取。部署文档理解时要分别验证文本层、扫描识别、表格结构与字段准确性。界面截图的理解也要跟随实际控件和状态变化。

历史 gpt-4-vision-preview 接口已停止服务。选择模型时查看供应商当前支持的模态、输入方式和限制。Pillow 对象是本机内存表示。发送 URL 或 data URI 前先检查可访问范围、媒体类型和格式。本站复跑此前的真实 SDK 请求构造,检查白底合成、缩放、JPEG 解码及请求体像素,请求由本机固定传输拦截。

语音识别、意图和有声回复分开

语音流程通常包括 ASR、意图解析、对话管理与可选 TTS。本站先用 eSpeak NG 生成单声道 PCM WAV,再由 FFmpeg 统一到 16 kHz 供 PocketSphinx 解码。语音与直接文字共用同一意图路由。只有允许播报的回复才生成 WAV。

在固定英语语法与合成语音下,go forward 和 turn left 得到完整识别。stop now 实际只返回 go,程序将它视作未识别指令,仅给出文字提示,不生成语音回复或执行动作。直接输入完整的 stop now 会进入已记录停止的分支。

WAV 和 MP3 是输入格式,解码后还需核对采样率和声道。真实交互另验噪声、口音、静音、麦克风、模型质量和合成声音选择。Whisper 与 DeepSpeech 是历史示例提及的识别方案。更换识别或合成组件时要核对模型版本与许可、接口、支持语种及同一组输入的表现。

按时间轴核对视频帧、音轨和字幕

视频可均匀采样,也可根据画面变化选取代表帧。均匀采样便于比较固定间隔,变化筛选更容易定位短事件。本站从实际解码帧和显示时间戳读取标记,逐帧检测位置后才汇总,1 秒处标记从左移到右。

本站视频以每秒 4 帧生成 8 帧,并将音轨对齐在同一时间线。解码后分别测量移动前后音量。浏览器跳到 0.5 秒或 1.5 秒,画布读取真实解码像素,分别观察标记列 16 与 56,并显示与时间匹配的字幕。下图来自本站浏览器实跑。

本站页面在 1.5 秒显示标记列 56 和右侧提示音字幕
本站浏览器实际解码帧。时间为 1.5 秒,标记位于第 56 列,字幕对应右侧提示音。

光流估计像素运动向量。本站只测固定色块位置变化,不能推断复杂运动。真实长视频需处理可变帧率、遮挡、音画偏移和计算成本。用取样预算、时间戳和准确的证据片段支持后续核查。

给应用设定独立验收目标

智能相册可用场景、人物或事件组织检索,需验证分类准确率和个人数据权限。视频摘要要能回到关键片段与时间。无障碍辅助应给用户清楚的描述、可暂停的语音和可纠正的结果。会议助手需要区分说话者、记录待办与证据,并核对参与者授权。

本章验证受控图像、音频与时间线。真实视觉语义、字幕识别、会议纪要和业务副作用分别验证后才能扩展使用。

实际解码图表和视听片段

含完整源码 · 155 行
展开查看收起
python
"""Measure a local PNG and decode a time-aligned video and audio fixture."""
from importlib.metadata import version
from math import pi,sin,sqrt
from pathlib import Path
import re
import struct
import subprocess
import sys
import wave

from imageio_ffmpeg import get_ffmpeg_exe
from PIL import Image,ImageDraw

from lab_tools import run_exercise


SIZE=(96,64)
BAR_COLOR=(28,104,156)
CENTERS=(60,160,260)


def run_ffmpeg(*arguments):
    return subprocess.run([get_ffmpeg_exe(),"-hide_banner","-nostdin",*map(str,arguments)],
                          capture_output=True,encoding=None,timeout=25,check=True)


def chart(path,heights):
    image=Image.new("RGB",(320,160),"white")
    draw=ImageDraw.Draw(image)
    for x,height in zip(CENTERS,heights,strict=True):
        draw.rectangle((x-15,130-height,x+15,129),fill=BAR_COLOR)
        draw.text((x-10,135),str(x),fill="black")
    draw.line((20,130,300,130),fill="black")
    image.save(path)


def measure_chart(path):
    with Image.open(path) as image:
        if image.format!="PNG" or image.size!=(320,160):
            raise ValueError("unexpected chart fixture")
        rgb=image.convert("RGB")
        return [sum(rgb.getpixel((x,y))==BAR_COLOR for y in range(36,130)) for x in CENTERS]


def assess(heights,limit):
    return {"bars":heights,"threshold":limit,"over_limit":[index+1 for index,value in enumerate(heights) if value>limit]}


def build_video(root):
    width,height=SIZE
    frames=[]
    for index in range(8):
        image=Image.new("RGB",SIZE,(220,220,220))
        center=16 if index<4 else 56
        ImageDraw.Draw(image).rectangle((center-8,24,center+7,39),fill=(200,20,20))
        frames.append(image.tobytes())
    raw=root/"frames.rgb"
    raw.write_bytes(b"".join(frames))
    tone=root/"timeline.wav"
    pcm=[0]*16000+[round(11000*sin(2*pi*440*i/16000)) for i in range(16000)]
    with wave.open(str(tone),"wb") as audio:
        audio.setparams((1,2,16000,0,"NONE","not compressed"))
        audio.writeframes(struct.pack("<"+"h"*len(pcm),*pcm))
    target=root/"timeline.mp4"
    run_ffmpeg("-loglevel","error","-y","-f","rawvideo","-pixel_format","rgb24","-video_size",
               f"{width}x{height}","-framerate","4","-i",raw,"-i",tone,"-c:v","libx264",
               "-threads","1","-pix_fmt","yuv420p","-c:a","aac","-map_metadata","-1","-movflags","+faststart",target)
    return target


def decode_video(path):
    width,height=SIZE
    data=run_ffmpeg("-loglevel","error","-i",path,"-map","0:v:0","-f","rawvideo","-pix_fmt","rgb24","-").stdout
    size=width*height*3
    assert len(data)%size==0
    centers=[]
    for offset in range(0,len(data),size):
        frame=Image.frombytes("RGB",SIZE,data[offset:offset+size])
        points=[x for x in range(width) if (pixel:=frame.getpixel((x,32)))[0]>140 and max(pixel[1:])<90]
        assert points
        centers.append(round(sum(points)/len(points)))
    timing=run_ffmpeg("-i",path,"-map","0:v:0","-vf","showinfo","-f","null","-").stderr.decode(errors="replace")
    stamps=[float(value) for value in re.findall(r"\bn:\s*\d+\s+pts:\s*\d+\s+pts_time:([0-9.]+)",timing)]
    assert len(centers)==len(stamps)
    return centers,stamps


def audio_windows(path):
    data=run_ffmpeg("-loglevel","error","-i",path,"-map","0:a:0","-ac","1","-ar","16000","-f","s16le","-").stdout
    samples=[value for value, in struct.iter_unpack("<h",data)]
    def rms(start,end):
        segment=samples[round(start*16000):round(end*16000)]
        return sqrt(sum(sample*sample for sample in segment)/len(segment))
    return rms(0.1,0.8),rms(1.2,1.8)


def exercise(checks,root,export=None):
    expect=checks.expect
    image=root/"harbor-bars.png"
    chart(image,[24,48,72])
    actual=measure_chart(image)
    expect("media_chart_pixels",[24,48,72],"Decode actual PNG pixels at three declared bar centers",
           [24,48,72],actual)
    expect("media_mixed_threshold",{"question":"bars strictly higher than 48","threshold":48},
           "Combine image measurements with a threshold and retain the evidence values",
           {"bars":[24,48,72],"threshold":48,"over_limit":[3]},assess(actual,48))
    changed=root/"changed.png"
    chart(changed,[24,60,72])
    expect("media_image_change",[24,60,72],"Read a changed input image and recompute the same task",
           [2,3],assess(measure_chart(changed),48)["over_limit"])
    doc=root/"document-preview.png"
    screenshot=Image.new("RGB",(320,160),"white")
    draw=ImageDraw.Draw(screenshot)
    draw.text((20,20),"Dock log A7",fill="black")
    draw.rectangle((18,54,301,132),outline="black",width=2)
    draw.line((150,54,150,132),fill="black",width=2)
    draw.text((22,63),"Reading",fill="black")
    draw.text((165,63),"40",fill="black")
    screenshot.save(doc)
    with Image.open(doc) as page:
        top=page.crop((20,20,160,46))
        table=page.crop((18,54,302,133))
        actual_regions=[list(top.size),list(table.size),top.convert("L").getextrema()[0]<255,
                        table.getpixel((0,0))==(0,0,0)]
    expect("media_document_regions","self-authored raster document","Separate title and table regions without claiming OCR",
           [[140,26],[284,79],True,True],actual_regions)

    clip=build_video(root)
    positions,stamps=decode_video(clip)
    expect("media_video_timestamps",{"frames":8,"fps":4},"Decode actual frame positions and presentation timestamps",
           [[16]*4+[56]*4,[0,0.25,0.5,0.75,1,1.25,1.5,1.75]],[positions,stamps])
    uniform=[[stamps[i],positions[i]] for i in range(0,len(stamps),2)]
    changes=[[stamps[i],positions[i]] for i in range(1,len(stamps)) if abs(positions[i]-positions[i-1])>=20]
    expect("media_video_sampling","uniform every two frames and threshold change",
           "Compare sampled positions and identify the first large marker movement",
           [[[0,16],[0.5,16],[1,56],[1.5,56]],[[1,56]]],[uniform,changes])
    quiet,loud=audio_windows(clip)
    expect("media_video_audio_alignment","before and after the marker switches at 1 second",
           "Decode the actual audio track and compare RMS windows on the same timeline",
           [True,True],[quiet<200,loud>5000])
    expect("media_video_runtime","installed codecs and wrapper","Record native FFmpeg and Pillow versions",
           ["0.6.0","13.0.0",True],[version("imageio-ffmpeg"),version("Pillow"),
             run_ffmpeg("-version").stdout.startswith(b"ffmpeg version ")])
    if export is not None:
        for path in (image,doc,clip):
            (export/path.name).write_bytes(path.read_bytes())


if __name__=="__main__":
    if len(sys.argv)==3 and sys.argv[1]=="--export":
        output=Path(sys.argv[2])
        run_exercise(lambda checks,root:exercise(checks,root,output))
    else:
        run_exercise(exercise)
固定 PNG 的三个柱高可以复算,视频在 1 秒切换标记,语音误识别不会触发动作。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

运行和核对本机媒体

ZIP 含本站源代码、两幅 PNG、实际语音 WAV、短视频和交互页。

下载本章实验包 (mbskycom202612a3073.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3093.zip

常见错误与边界检查

  • 固定图像测量方法依赖已知布局。
  • 短语语法、输入采样和识别准确性是独立条件。

技术规范与官方资料

练习与参考解答

查看参考解答

两个时间点各有不同的标记和字幕。本机语音程序会把不完整识别结果留作失败证据。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习