This repository has been archived on 2026-10-21. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
PICKA_python/tools/segment_extract.py
T
2026-09-22 11:52:03 +02:00

232 lines
10 KiB
Python

import csv
import json
import os
import datetime
import ffmpeg
import re
import subprocess
import time
import multiprocessing
from contextlib import contextmanager
from functools import partial
stream_segments = []
def getGame(angle, game, s, iface, f, subject, upper):
if upper:
game = game.upper()
else:
game = game.capitalize()
try:
if angle in s[iface][game].keys():
for seg, time in s[iface][game][angle]["times"].items():
stream_segments.append(create_streams(
f, time, subject, iface, game, angle, seg))
except KeyError:
pass
def extract_durations(fpath):
timestamps = {}
with open(fpath) as csvfie:
reader = csv.reader(csvfie)
for n, row in enumerate(reader):
if not n:
continue
subject, _, iface, angle, segment, game, start, end, duration = row
if subject not in timestamps:
timestamps[subject] = {}
if iface not in timestamps[subject]:
timestamps[subject][iface] = {}
if game not in timestamps[subject][iface]:
timestamps[subject][iface][game] = {}
if angle not in timestamps[subject][iface][game]:
timestamps[subject][iface][game][angle] = {}
if "times" not in timestamps[subject][iface][game][angle]:
timestamps[subject][iface][game][angle]["times"] = {}
if segment not in timestamps[subject][iface][game][angle]["times"]:
timestamps[subject][iface][game][angle]["times"][segment] = {}
if start not in timestamps[subject][iface][game][angle]["times"][segment]:
timestamps[subject][iface][game][angle]["times"][segment]["start"] = start
if end not in timestamps[subject][iface][game][angle]["times"][segment]:
timestamps[subject][iface][game][angle]["times"][segment]["end"] = end
if duration not in timestamps[subject][iface][game][angle]["times"][segment]:
timestamps[subject][iface][game][angle]["times"][segment]["duration"] = duration
os.chdir("/Volumes/LaCie/Videos to analyse/Separate videos/to split/")
cwd = os.getcwd()
files = os.listdir(cwd)
subject = ''
for f in files:
s = None
for subject in timestamps:
# with poolcontext as pool:
stream = ""
# o = subprocess.check_output(
# ["ffprobe", "-hide_banner", f], stderr=subprocess.STDOUT)
# mediaprobe_re = re.compile(
# r"Duration:\s+(?P<dur>(?:(?:\d:?)+[.]?\d*)|N/A)(?:.+start:\s+(?P<start>\d+[.]\d+))?.+bitrate:\s+(?P<bitrate>(?:\d+\s*..[/]s)|N/A)")
# probe = mediaprobe_re.findall(o.decode("utf-8"))
# duration = datetime.datetime.strptime(probe[0][0], "%H:%M:%S.%f")
# d_hour, d_min, d_sec = duration.hour, duration.minute, duration.second
if subject in f:
if not s:
for k, v in timestamps.items():
if k in f:
subject = k
s = timestamps[k]
break
if "lap" in f.lower():
if "front" in f.lower():
getGame("front", "crm", s, "lap", f, subject, True)
getGame("front", "emotion", s,
"lap", f, subject, False)
getGame("front", "jnd", s, "lap", f, subject, True)
getGame("front", "gender", s,
"lap", f, subject, False)
# a = 'front'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
if "side" in f.lower():
getGame("side", "crm", s, "lap", f, subject, True)
getGame("side", "emotion", s,
"lap", f, subject, False)
getGame("side", "jnd", s, "lap", f, subject, True)
getGame("side", "gender", s,
"lap", f, subject, False)
# a = 'side'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
elif "sam" in f.lower():
if "front" in f.lower():
getGame("front", "crm", s, "sam", f, subject, True)
getGame("front", "emotion", s, "sam", f, subject, False)
getGame("front", "jnd", s, "sam", f, subject, True)
getGame("front", "gender", s, "sam", f, subject, False)
# a = 'front'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# try:
# game = "PICKA"
# for seg, time in s[iface][game][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# except KeyError:
# pass
if "side" in f.lower():
getGame("side", "crm", s, "sam", f, subject, True)
getGame("side", "emotion", s,
"sam", f, subject, False)
getGame("side", "jnd", s, "sam", f, subject, True)
getGame("side", "gender", s,
"sam", f, subject, False)
# a = 'side'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# try:
# game = "PICKA"
# for seg, time in s[iface][game][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# except KeyError:
# pass
return stream_segments
@contextmanager
def poolcontext(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
def run_ffmpeg(stream_segment, dirpath):
save_path = "/Volumes/LaCie/Videos to analyse/Separate videos/split/" + \
dirpath + "/extracted/"
stream = stream_segment[0]
fname = save_path + stream_segment[1] + ".mp4"
if not os.path.exists(fname):
stream = ffmpeg.output(stream, fname, **{"async": 1})
# stream = ffmpeg.overwrite_output(stream)
print(stream)
ffmpeg.run(stream)
def create_fname(subject, iface, game, angle, segment):
return "{}-{}-{}-{}-{}".format(subject, iface, angle, game, segment)
def create_streams(filename, times, subject, iface, game, angle, segment):
s = ffmpeg.input(filename, ss=times["start"], to=times["end"])
f = create_fname(subject, iface.capitalize(), game, angle, segment)
return s, f
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-t", "--tstamps", default="/Users/lukemeyer/Desktop/RUG/PhD/Results/Experiment_1/Video Coding/timestamps2.csv")
parser.add_argument("-d", "--dirpath", required=True)
args = parser.parse_args()
stream_segments = extract_durations(args.tstamps)
with poolcontext() as pool:
for x in pool.imap(partial(run_ffmpeg, dirpath=args.dirpath), stream_segments, chunksize=1):
time.sleep(1)
# print(json.dumps(timestamps, sort_keys=True, indent=4))