"""Inspect the single registered recording; never import/run a transcription model."""
import array, csv, hashlib, json, math, pathlib, struct, subprocess, sys, zlib
D=pathlib.Path(__file__).parent
src=D/'source-kick.ogg'
sha=lambda b:hashlib.sha256(b).hexdigest()
assert sha(src.read_bytes())=='f2ac32d4275532460820ec289cdf351f92788e66f44e5ad6149c83deb33a993f'
ff=pathlib.Path('D:/AudioToMidiNow/ops/research/daily-2026-10-29/tools/node_modules/@ffmpeg-installer/win32-x64/ffmpeg.exe')
protocol={'purpose':'Pre-conversion waveform/onset-candidate inspection of one original bass-drum recording; not model accuracy or classified MIDI output',
 'sample':'source-kick.ogg','sourceSHA256':sha(src.read_bytes()),'decoder':'Existing FFmpeg; mono f32le44100Hz analysis representation only, full clip/no crop',
 'frameSamples':441,'frameSeconds':0.01,'candidateThreshold':'0.10 * maximum absolute decoded sample amplitude',
 'mergeGapSeconds':0.20,'onsetRule':'First above-threshold sample after at least0.20s without another above-threshold sample',
 'boundaryLimit':'These signal-threshold candidates are not manually or hardware annotated strike ground truth and must not become gold labels without review',
 'independentMatchingPlan':'If reviewed references are frozen and a browser MIDI exists, nearest unused same drum class onset within50ms; separately count time-only matches and intended kit-note/channel assignments',
 'noTranscriptionOrMIDIExport':True,'newSampleBudget':1,'noSecondSampleOrMode':True}
(D/'source-inspection-protocol.json').write_text(json.dumps(protocol,indent=2)+'\n',encoding='utf-8')
raw=subprocess.run([str(ff),'-hide_banner','-loglevel','error','-i',str(src),'-ac','1','-ar','44100','-f','f32le','-'],check=True,capture_output=True).stdout
(D/'source-analysis-f32le.pcm').write_bytes(raw)
x=array.array('f');x.frombytes(raw)
if sys.byteorder!='little':x.byteswap()
peak=max(map(abs,x));threshold=peak*.1;rate=44100
candidates=[];previous=None
for i,v in enumerate(x):
 if abs(v)>=threshold:
  if previous is None or (i-previous)/rate>.20:candidates.append({'sampleIndex':i,'seconds':i/rate,'kind':'signal-threshold candidate, bass-drum source category only'})
  previous=i
envelope=[]
for i in range(0,len(x),441):
 frame=x[i:i+441]
 envelope.append({'startSeconds':i/rate,'endSeconds':(i+len(frame))/rate,'peak':max(map(abs,frame)),'rms':math.sqrt(sum(v*v for v in frame)/len(frame))})
with (D/'source-envelope.csv').open('w',newline='',encoding='utf-8')as f:
 w=csv.DictWriter(f,fieldnames=list(envelope[0]));w.writeheader();w.writerows(envelope)
report={'result':'SOURCE_WAVEFORM_INSPECTED_NO_MODEL_EXECUTED','sampleRate':rate,'decodedMonoFrames':len(x),'durationSeconds':len(x)/rate,'peakAbsolute':peak,'thresholdAbsolute':threshold,'thresholdCandidates':candidates,'candidateCount':len(candidates),'rmsWindowSeconds':.01,'protocol':'source-inspection-protocol.json','sourceSHA256':sha(src.read_bytes()),'decodedPCM_SHA256':sha(raw),'ffmpegSHA256':sha(ff.read_bytes()),'audioRepresentationOnly':True,'referenceGroundTruthVerified':False,'modelExecutions':0,'browserConversions':0,'noteAccuracy':'NOT_MEASURED'}
(D/'source-inspection.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
# A standalone scientific plot, drawn from the measured envelope using only stdlib.
W,H=1200,340;rgb=bytearray([12,20,28])*(W*H)
def pixel(a,b,c):
 if 0<=a<W and 0<=b<H:rgb[(b*W+a)*3:(b*W+a)*3+3]=bytes(c)
for k in range(1,6):
 a=int(40+k/6*(W-80))
 for b in range(20,H-20):pixel(a,b,(40,55,64))
for j,e in enumerate(envelope):
 a=40+int(j/max(1,len(envelope)-1)*(W-80));height=int(e['peak']/peak*(H/2-30))
 for b in range(H//2-height,H//2+height+1):pixel(a,b,(110,242,194))
for c in candidates:
 a=40+int(c['seconds']/(len(x)/rate)*(W-80))
 for b in range(15,H-15):pixel(a,b,(244,153,80))
def chunk(t,b):return struct.pack('>I',len(b))+t+b+struct.pack('>I',zlib.crc32(t+b)&0xffffffff)
png=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',W,H,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(b''.join(b'\0'+rgb[y*W*3:(y+1)*W*3]for y in range(H))))+chunk(b'IEND',b'')
(D/'source-envelope.png').write_bytes(png)
svg='<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="420" viewBox="0 0 1200 420"><rect width="1200" height="420" fill="#0c141c"/><text x="40" y="28" fill="white" font-family="sans-serif" font-size="20">Bass-drum source: 10ms peak envelope; orange lines are threshold candidates, not gold labels</text>'
for j,e in enumerate(envelope):
 a=40+j/max(1,len(envelope)-1)*1120;h=e['peak']/peak*135
 svg+=f'<line x1="{a:.3f}" x2="{a:.3f}" y1="{205-h:.3f}" y2="{205+h:.3f}" stroke="#6ef2c2" stroke-width="2"/>'
for c in candidates:
 a=40+c['seconds']/(len(x)/rate)*1120
 svg+=f'<line x1="{a:.3f}" x2="{a:.3f}" y1="50" y2="350" stroke="#f49950"/><text x="{a:.3f}" y="375" fill="white" font-family="sans-serif">{c["seconds"]:.4f}s</text>'
svg+=f'<text x="40" y="405" fill="white" font-family="sans-serif">44100Hz mono analysis; duration {len(x)/rate:.6f}s; original OGG unchanged; no inference performed</text></svg>'
(D/'source-envelope.svg').write_text(svg,encoding='utf-8')
print(json.dumps(report))
