图像、音频与视频的输入契约:练习答案
参考实现
复用正文函数:
python
def duration_ms(byte_count, sample_rate, channels, sample_width):
frame = channels * sample_width
if min(sample_rate,channels,sample_width)<=0 or byte_count<0 or byte_count%frame:
raise ValueError('invalid PCM geometry')
return byte_count / frame / sample_rate * 1000
assert duration_ms(4800,24000,1,2) == 100
assert duration_ms(4800,16000,1,2) == 150
try:
duration_ms(3,24000,1,2)
except ValueError:
pass
else:
raise AssertionError('partial sample accepted')
print('PCM geometry passed')
one_second = 48000*2*2
assert one_second == 192000
assert duration_ms(one_second,48000,2,2)==1000MP3是压缩码流,字节率与解码采样帧不同,文件还含头部与元数据;需读取容器/编码时间信息或解码后计算。
返回题目。
媒体文件变体
保存 answer_media.py,在正文numpy/scipy环境运行:
python
import numpy as np
from scipy.signal import resample_poly
box=(100,40,220,100)
assert (box[0]+30/3,box[1]+30/3)==(110,50)
samples=.2*np.sin(2*np.pi*440*np.arange(24000)/24000)
out=resample_poly(samples,2,3)
encoded=(np.clip(out,-1,1)*32767).astype('<i2').tobytes()
assert len(out)/16000==1 and len(encoded)==32000
pts=[i/10 for i in range(10)]
assert next(t for t in pts if t>=.35)==.4
print('coordinate and resampling variants passed')选择0.4秒帧是“首个不早于目标”规则;如果任务要求最近帧,则0.3与0.4的等距情况还要定义决胜规则。packet可能含压缩依赖,不能按网络到达数量解释帧时间。
媒体检索引用变体
将正文保存为media_retrieval.py,答案保存为retrieval_answers.py,同目录用相同真实媒体/OCR环境运行。
python
from media_retrieval import build,index,retrieve,citation
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as directory:
rows,version=build(Path(directory));db=index(rows)
hits=retrieve(db,'ORDER 42 HOLD','A',version)
assert len(hits)==1
result=citation(db,hits[0]['id'],hits,'A',version)
assert result['frame']==1 and result['time']==1
# 取回已授权快照后原文件发生变化,旧引用必须失效。
source=Path(result['source']);source.write_bytes(source.read_bytes()+b'changed')
try:citation(db,hits[0]['id'],hits,'A',version)
except ValueError as e:assert 'version changed' in str(e)
else:raise AssertionError('stale media accepted')
db.execute('UPDATE metadata SET deleted=1 WHERE id=?',(hits[0]['id'],));db.commit()
assert retrieve(db,'ORDER 42 HOLD','A',version)==[]
try:citation(db,hits[0]['id'],hits,'A',version)
except ValueError as e:assert 'revoked' in str(e)
else:raise AssertionError('deleted snapshot accepted')
db.close()
print('second frame, media mutation and tombstone variants passed')ORDER42HOLD只是某个视频版本在1秒处的文字,不能证明查询当下的业务状态。归档视频不是订单系统;自然语言改写与OCR字符串不完全一致时,当前整词索引可能未命中,需另加召回方案并验证,不应把空召回当“订单不存在”。