import cv2
import pickle
import traceback

try:
    with open('unique_pages.pkl', 'rb') as f:
        unique_pages = pickle.load(f)
except Exception:
    import video_cv_tracker as tracker_lib
    from youtube_tab_to_pdf import _find_white_tab_strip
    tracker = tracker_lib.TemporalTracker(diff_threshold=0.05)
    video = cv2.VideoCapture("output/shintakarajima.mp4")
    
    # Just read 100 frames
    frames = []
    fps_orig = video.get(cv2.CAP_PROP_FPS)
    stride = max(1, int(fps_orig / 4.0))
    count = 0
    while len(frames) < 150:
        ret, f = video.read()
        if not ret: break
        if count % stride == 0: frames.append(f)
        count += 1
    video.release()
    
    top, bottom = 0, frames[0].shape[0]
    for f in frames[::10]:
        b = _find_white_tab_strip(f)
        if b:
            top, bottom = b
            break
            
    for f in frames:
        tracker.process_frame(f[top:bottom, :])
        
    unique_pages = tracker.get_unique_pages()
    with open('unique_pages.pkl', 'wb') as f:
        pickle.dump(unique_pages, f)

from score_extractor import ScoreExtractor
ex = ScoreExtractor()
try:
    print(f"Running ScoreExtractor on {len(unique_pages)} pages...")
    ex.process_pages(unique_pages)
    print("Success!")
except Exception as e:
    print("CRASHED:")
    traceback.print_exc()
