textgrid_dir = "/Users/joregan/Playing/textgrids_shared"
timecode_dir = "/Users/joregan/timecode_cut"
output_dir = "/tmp/textgrid_cut"
from pathlib import Path

textgrid_path = Path(textgrid_dir)
timecode_path = Path(timecode_dir)
output_path = Path(output_dir)
def get_timecode_offsets(filename):
    if type(filename) == Path:
        filename = str(filename)

    with open(filename) as inf:
        lines = [l.strip() for l in inf.readlines()]
        assert lines[0] == ",Frame,Time (Seconds),TimeCode", f"CSV file ({filename}) seems to be incorrect"
        p_start = lines[1].split(",")
        start = float(p_start[2])
        p_end = lines[-1].split(",")
        end = float(p_end[2])
        return start, end
from praatio import textgrid
from praatio.utilities.constants import Interval

def modify_textgrid(filename, start, end, output=None):
    if type(filename) == Path:
        filename = str(filename)
    if not output:
        output = filename
    elif type(output) == Path:
        output = str(output)

    tg = textgrid.openTextgrid(filename, True)
    new_tg = textgrid.Textgrid()
    for tiername in tg.tierNames:
        tier = tg.getTier(tiername)
        new_entries = []
        for entry in tier.entries:
            e_start = entry[0]
            e_end = entry[1]
            e_text = entry[2]

            new_start = e_start - start
            new_end = e_end - start

            if new_end < 0.0:
                continue
            elif e_start >= end and e_end > end:
                continue
            elif new_start < 0.0 and new_end > 0.0:
                if e_text != "":
                    print("Warning: truncating entry", filename, tiername, entry)
                if new_entries == []:
                    new_entries.append(Interval(0.0, new_end, e_text))
                else:
                    print("Shouldn't have existing entries!!", entry)
                    new_entries.append(Interval(0.0, new_end, e_text))
            elif e_start >= start and e_end <= end:
                new_entries.append(Interval(new_start, new_end, e_text))
            elif e_start <= end and e_end > end:
                if e_text != "":
                    print("Warning: truncating entry", filename, tiername, entry)
                new_entries.append(Interval(new_start, new_end, e_text))
            else:
                print("There should be no default case", entry)

        tier_start = new_entries[0][0]
        tier_end = new_entries[-1][1]
        new_tier = textgrid.IntervalTier(tiername, new_entries, tier_start, tier_end)
        new_tg.addTier(new_tier)

    new_tg.save(output, format="long_textgrid", includeBlankSpaces=True)
if not output_path.is_dir():
    output_path.mkdir()

for tgfile in textgrid_path.glob("*.[Tt]ext[Gg]rid"):
    base_stem = tgfile.stem
    stem = base_stem
    if "_inter" in stem:
        stem = stem.replace("_inter", "")
    else:
        stem = stem.replace("_main", "")

    csv_file = timecode_path / f"{stem}.csv"

    if not csv_file.exists():
        print("No timecode for", tgfile)
        continue

    start, end = get_timecode_offsets(csv_file)
    output_file = output_path / f"{base_stem}.TextGrid"
    modify_textgrid(tgfile, start, end, output_file)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_002_main.TextGrid words Interval(start=16.8636, end=17.4336, label='yes')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_002_main.TextGrid phones Interval(start=17.2136, end=17.4336, label='S')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_002_main.TextGrid utterances Interval(start=16.7036, end=19.5846, label='Oh, yes, you know, it was really expensive property.')
Textgrid has a max timestamp of (477.8844) but tier has (477.84439999999995)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_227_002_inter.TextGrid utterances Interval(start=23.002, end=25.6718, label="Ok, that's a very nice apartment you have here.")
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_5_0718_209_001_main.TextGrid words Interval(start=25.5632, end=26.0332, label='yes')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_5_0718_209_001_main.TextGrid phones Interval(start=25.8132, end=26.0332, label='S')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_5_0718_209_001_main.TextGrid utterances Interval(start=25.5332, end=26.1542, label='Yes.')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_227_002_main.TextGrid words Interval(start=785.9736, end=786.4836, label='yes')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_227_002_main.TextGrid phones Interval(start=786.2436, end=786.4836, label='S')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_227_002_main.TextGrid utterances Interval(start=785.9436, end=786.5205, label='Yes.')
Maximum timestamp in Textgrid changed from (762.8836) to (762.9205)
Textgrid has a max timestamp of (762.9205) but tier has (762.8836)
Textgrid has a max timestamp of (762.9205) but tier has (762.8836)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_3_0715_227_003_main.TextGrid words Interval(start=364.524, end=365.104, label='cloth')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_3_0715_227_003_main.TextGrid phones Interval(start=364.904, end=365.104, label='TH')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_3_0715_227_003_main.TextGrid utterances Interval(start=363.444, end=365.1383, label='yeah the dry cloth')
Maximum timestamp in Textgrid changed from (342.37899999999996) to (342.4133)
Textgrid has a max timestamp of (342.4133) but tier has (342.37899999999996)
Textgrid has a max timestamp of (342.4133) but tier has (342.37899999999996)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_227_003_inter.TextGrid utterances Interval(start=12.6956, end=13.9728, label='[laughter]')
Textgrid has a max timestamp of (556.9694) but tier has (556.8931)
Textgrid has a max timestamp of (326.3542) but tier has (326.2242)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_210_001_main.TextGrid words Interval(start=351.8989, end=352.1189, label='really')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_210_001_main.TextGrid phones Interval(start=351.9589, end=352.0889, label='L')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_210_001_main.TextGrid utterances Interval(start=338.0789, end=352.4283, label="sometimes when I am reading and I feel that I don't have that much light [smack] I just turn that on. But uh otherwise I just keep this setup here with the small lamp and the chair and I just read something have a glass of wine or something that's really nice.")
Maximum timestamp in Textgrid changed from (326.3109) to (326.6203)
Textgrid has a max timestamp of (326.6203) but tier has (326.3109)
Textgrid has a max timestamp of (326.6203) but tier has (326.28090000000003)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_6_0718_209_001_inter.TextGrid utterances Interval(start=49.3559, end=52.9357, label="So yeah. Hi. It's like it looks like a very nice place you have here.")
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_002_inter.TextGrid utterances Interval(start=492.1993, end=492.533, label='Okay.')
Textgrid has a max timestamp of (475.61699999999996) but tier has (475.116)
Textgrid has a max timestamp of (402.2441) but tier has (402.2041)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_211_002_main.TextGrid words Interval(start=12.2553, end=13.0253, label='yeah')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_211_002_main.TextGrid phones Interval(start=12.2553, end=12.4853, label='Y')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_211_002_main.TextGrid utterances Interval(start=12.2153, end=15.154, label='Yeah, the location is amazing.')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_209_001_inter.TextGrid words Interval(start=419.0666, end=419.2966, label='yeah')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_209_001_inter.TextGrid phones Interval(start=419.0966, end=419.2966, label='AE1')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_209_001_inter.TextGrid utterances Interval(start=417.9366, end=421.153, label='Okay, but yeah, yeah good luck with your new apartment.')
Maximum timestamp in Textgrid changed from (400.8546) to (402.711)
Textgrid has a max timestamp of (402.711) but tier has (400.8546)
Textgrid has a max timestamp of (402.711) but tier has (400.8546)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_004_inter.TextGrid words Interval(start=526.6572, end=526.9472, label='mm')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_004_inter.TextGrid phones Interval(start=526.6572, end=526.9472, label='M')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_004_inter.TextGrid utterances Interval(start=526.6572, end=526.976, label='Mm.')
Maximum timestamp in Textgrid changed from (510.08019999999993) to (510.109)
Textgrid has a max timestamp of (510.109) but tier has (510.08019999999993)
Textgrid has a max timestamp of (510.109) but tier has (510.08019999999993)
No timecode for /Users/joregan/Playing/textgrids_shared/hsi_7_0719_209_002_main.TextGrid
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_210_002_main.TextGrid utterances Interval(start=26.6766, end=31.4251, label='Yeah, I mean, I think uh you can give you some, you can give it some personal touches.')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_5_0718_227_001_main.TextGrid utterances Interval(start=80.3311, end=80.9161, label='[sniff]')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_210_002_inter.TextGrid utterances Interval(start=316.3403, end=316.6525, label='[laughter]')
Maximum timestamp in Textgrid changed from (289.7103) to (289.9525)
Textgrid has a max timestamp of (289.9525) but tier has (289.7103)
Textgrid has a max timestamp of (289.9525) but tier has (289.7103)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_209_003_main.TextGrid utterances Interval(start=14.124, end=14.9584, label='[breath]')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_211_004_main.TextGrid words Interval(start=8.8791, end=9.0691, label='yeah')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_211_004_main.TextGrid phones Interval(start=8.8791, end=9.0291, label='Y')
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_211_004_main.TextGrid utterances Interval(start=8.8491, end=18.6244, label="Yeah, I mean, you have uh had a short stay here, but uh w- why would you like to leave? I mean, I I don't understand it. Everything is... so nice in this apartment.")
Textgrid has a max timestamp of (326.2203) but tier has (326.1603)
Textgrid has a max timestamp of (405.80640000000005) but tier has (405.7764)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_210_003_inter.TextGrid utterances Interval(start=13.8681, end=14.333, label='So.')
Textgrid has a max timestamp of (327.7199) but tier has (327.6499)
Warning: truncating entry /Users/joregan/Playing/textgrids_shared/hsi_7_0719_222_004_main.TextGrid utterances Interval(start=518.185, end=531.308, label='But maybe maybe if you if you put a small table, like two small tables next, I mean, i- on both sides of the fireplace, then maybe you can put them and then they will have this beige... Eh, it went off.')
Maximum timestamp in Textgrid changed from (510.16799999999995) to (514.441)
Textgrid has a max timestamp of (514.441) but tier has (510.16799999999995)
Textgrid has a max timestamp of (514.441) but tier has (510.16799999999995)
Textgrid has a max timestamp of (559.4114999999999) but tier has (559.3415)