from feat import Detector
from feat.utils.io import get_test_data_path
from moviepy.video.io.VideoFileClip import VideoFileClip
import os

def extract_aus(path, model, skip_frames):
  detector = Detector(au_model=model)

  video_prediction = detector.detect(
      path, data_type="video", skip_frames=skip_frames, face_detection_threshold=0.95 # alle 5 Sekunden einbeziehen - 24 Frames pro Sekunde
  )

  return video_prediction.aus.sum()

def split_video(path, chunk_length=120): 
    video = VideoFileClip(path)
    duration = int(video.duration)

    subclips_dir = os.path.join(os.dirname(path), "subclips")
    os.makedirs(subclips_dir, exist_ok=True)
    paths = []

    for start in range(0, duration, chunk_length):
        end = min(start + chunk_length, duration)

        subclip = (
            video
            .subclip(start, end)
            .without_audio()      
            .set_fps(video.fps)          
        )

        output_path = f"{subclips_dir}_part_{start//chunk_length + 1}.mp4"
        subclip.write_videofile(
           output_path, 
           )
        paths.append(output_path)

    return output_path

# def start(path):
#     results = []
#     clips = split_video(path)

#     for clip in clips:
#       results.append(extract_aus(clip, 'svm', 25*5))
#     return results

if __name__ == "__main__":
  results = []
  clips = []
  test_video_path = "AU_creation/YTDown.com_YouTube_Was-ist-los-bei-7-vs-Wild_Media_Gtj9zu_WikU_001_1080p.mp4"
  clips = split_video(test_video_path)

  for clippath in clips:
    results.append(extract_aus(clippath, 'svm', 25*5))

  print(results)