Import a Tidal Tales CSV export

Author

Michael Achmann-Denkler

Published

November 2, 2026

This notebook prepares a TikTok collection for the course’s OCR and audio preprocessing. It creates df_posts with the expected id, author, and body columns and prepares local media in the folder layout used by 2024_11_11_Preprocessing.ipynb.

The CSV contains metadata and file references, not the media themselves. Keep the original CSV and the downloaded tidaltales/ directory. This import does not download media, run OCR, transcribe audio, or call an API. It does not establish that the collection is complete or representative.

We use pandas and Pillow. If necessary, install them in your notebook environment with %pip install pandas pillow. In Colab, first mount Google Drive and copy both the CSV and the complete tidaltales/ directory there, preserving their relative paths. All paths below refer to the environment running this notebook.

1. Set your paths

MEDIA_ROOT is the directory containing tidaltales/, usually Firefox’s Downloads directory. OUTPUT_ROOT is a new working directory outside the website repository. Use a fresh output directory for each import to avoid mixing collections.

The default selects TikTok only. Apply your study’s account, date, and content inclusion criteria in section 2 before continuing. Preparing media copies one representative image and one video per post; check the required disk space first. Set PREPARE_MEDIA = False for a metadata-only check.

from pathlib import Path
import shutil
from urllib.parse import quote

import pandas as pd
from IPython.display import display
from PIL import Image

CSV_PATH = Path.home() / "Downloads" / "tidaltales_export_20261102T102111.csv"
MEDIA_ROOT = Path.home() / "Downloads"
OUTPUT_ROOT = Path.home() / "tidaltales-prepared"
PREPARE_MEDIA = True

MEDIA_ROOT = MEDIA_ROOT.expanduser().resolve()
OUTPUT_ROOT = OUTPUT_ROOT.expanduser().resolve()

2. Read and select observations

Read all columns as strings. TikTok IDs can exceed the precision of floating-point numbers, and empty captions must remain empty strings. utf-8-sig handles the export’s UTF-8 byte-order mark. The original exported columns, including raw JSON, remain in df_observations; we do not display raw JSON here.

The exporter may prefix spreadsheet-formula-like text with an apostrophe. This notebook preserves exported captions as provided; inspect such cases against the original metadata if exact text reconstruction matters.

df_observations = pd.read_csv(CSV_PATH, dtype=str, keep_default_na=False, encoding="utf-8-sig")
required = {"Platform", "Item ID", "Username", "Caption", "Collected At", "Image Paths", "Video Paths"}
missing = required - set(df_observations.columns)
if missing:
    raise ValueError(f"Missing Tidal Tales export columns: {sorted(missing)}")

selected = df_observations.loc[df_observations["Platform"].eq("TikTok")].copy()
# Apply your documented sampling criteria here, for example:
# selected = selected.loc[selected["Username"].isin(["account_a", "account_b"])].copy()
if selected.empty:
    raise ValueError("No TikTok records remain after filtering.")
if selected["Item ID"].str.strip().eq("").any():
    raise ValueError("Some selected records have no Item ID. Review them before importing.")
print(f"Read {len(df_observations)} observations; selected {len(selected)} TikTok observations.")

3. Review repeated captures

The following preprocessing uses one row per post. We therefore keep the latest captured observation for each (Platform, Item ID). Ties use the later CSV row. This is an explicit preparation choice, not a rule for longitudinal research. The selected row supplies both metadata and media paths; we do not combine measurements or file lists from different observations. An older observation may reference media missing from the latest one, so review duplicates before proceeding.

duplicate_observations.csv records all selected observations belonging to repeated IDs. The original CSV remains the full collection record.

selected["_captured_at"] = pd.to_datetime(selected["Collected At"], utc=True, errors="coerce")
keys = ["Platform", "Item ID"]
duplicates = selected.duplicated(keys, keep=False)
if (duplicates & selected["_captured_at"].isna()).any():
    raise ValueError("Repeated IDs have missing/invalid collection dates. Resolve these before choosing the latest capture.")
df_duplicates = selected.loc[duplicates].drop(columns="_captured_at").copy()
display(df_duplicates[["Item ID", "Username", "Collected At"]].head(10))
latest = (selected.sort_values("_captured_at", kind="stable", na_position="first")
          .drop_duplicates(keys, keep="last").drop(columns="_captured_at").reset_index(drop=True))
print(f"Prepared {len(latest)} unique posts; removed {len(selected) - len(latest)} repeated observations.")

4. Build the post table

Export column Preprocessing column Purpose
Item ID id Join OCR and transcription results to posts
Username author Match the prepared media subfolder
Caption body Caption text for the Text Master
Posted At / Collected At posted_at / collected_at Retain publication and capture times

username preserves the exported username. author uses a filesystem-safe encoding of that name (or a placeholder for missing names), matching the actual output folder. No OCR or transcription columns are filled with invented results. The remaining export columns retain their original names in the prepared table.

def folder_name(value):
    # Also encode dots so that values like '..' cannot become parent directories.
    return quote(value, safe="").replace(".", "%2E")

if not latest["Item ID"].str.fullmatch(r"[A-Za-z0-9_-]+").all():
    raise ValueError("Unexpected ID characters. Review IDs before using them as filenames.")

df_posts = latest.copy()
df_posts["id"] = latest["Item ID"]
df_posts["username"] = latest["Username"]
df_posts["author"] = latest["Username"].map(lambda name: folder_name(name) if name else "_unknown_author")
# Avoid a missing username colliding with a literal '_unknown_author' account.
df_posts.loc[latest["Username"].eq(""), "author"] = "%00unknown"
df_posts["body"] = latest["Caption"]
for source, target in [("Posted At", "posted_at"), ("Collected At", "collected_at")]:
    df_posts[target] = latest[source] if source in latest else ""

print(f"Empty captions: {df_posts['body'].str.strip().eq('').sum()}")
display(df_posts[["id", "username", "author", "posted_at"]].head())

5. Check media paths and select representative files

The export separates multiple paths with ;. Every listed image and video gets a row in df_media. File existence is checked locally, independently of the browser’s download status. Unverified legacy expected paths are not treated as downloaded files.

For compatibility with the older OCR loop, choose the first existing non-cover image in export order, falling back to an existing cover. For a video, that cover is only a still image: it does not represent all text shown during the video. For a photo gallery, this choice leaves other images out of the older OCR loop. All listed images remain in media_manifest.csv for a later analysis of every image. No video frame is extracted here.

The older video loop accepts MP4, AVI, MOV, and MKV; other formats remain in the manifest but are not prepared for that loop. A missing file, unsupported format, or failed image conversion must be reviewed rather than interpreted as absence of text or speech.

def split_paths(value):
    return list(dict.fromkeys(part.strip() for part in value.split("; ") if part.strip()))

def local_path(value):
    # Resolve relative paths under MEDIA_ROOT, including checking symbolic links.
    relative = Path(value)
    if relative.is_absolute():
        raise ValueError(f"Expected a relative media path: {value}")
    candidate = (MEDIA_ROOT / relative).resolve()
    if not candidate.is_relative_to(MEDIA_ROOT):
        raise ValueError(f"Media path leaves MEDIA_ROOT: {value}")
    return candidate

records = []
for row in df_posts.to_dict("records"):
    for kind, column in [("image", "Image Paths"), ("video", "Video Paths")]:
        for position, exported_path in enumerate(split_paths(row[column])):
            source = local_path(exported_path)
            records.append({"id": row["id"], "author": row["author"], "kind": kind,
                            "position": position, "exported_path": exported_path,
                            "local_path": str(source), "exists": source.is_file(),
                            "is_cover": source.stem.lower().endswith("_cover"),
                            "selected": False, "prepared_path": "", "status": "not selected"})

df_media = pd.DataFrame(records, columns=["id", "author", "kind", "position", "exported_path",
    "local_path", "exists", "is_cover", "selected", "prepared_path", "status"])
for (post_id, kind), group in df_media.groupby(["id", "kind"], sort=False):
    available = group.loc[group["exists"]]
    if kind == "image":
        preferred = available.loc[~available["is_cover"]]
        available = preferred if not preferred.empty else available
    else:
        available = available.loc[available["local_path"].map(
            lambda path: Path(path).suffix.lower() in {".mp4", ".avi", ".mov", ".mkv"})]
    if not available.empty:
        df_media.loc[available.index[0], "selected"] = True

df_media.loc[~df_media["exists"], "status"] = "missing"
df_media.loc[df_media["selected"], "status"] = "ready"
print(f"Listed media: {len(df_media)}; missing locally: {(~df_media['exists']).sum()}")
print(f"Representative files selected: {df_media['selected'].sum()}")
display(df_media.groupby(["kind", "status"]).size().rename("files").reset_index())

6. Prepare files and save the tables

Selected images are converted to JPEG so the older OCR loop can read formats such as WebP under a consistent <id>.jpg filename. Videos are copied without re-encoding. Originals are preserved. image_file and video_file contain prepared absolute paths; media_filename records the representative image filename.

The output contains posts.csv, a complete media manifest for the retained observations, and a duplicate-observation report. These files can contain research data and local paths: keep them outside the public website repository. Do not use the OCR and transcription loops until the media report matches your expectations.

# Refuse an existing output directory to prevent stale media from a prior run.
if OUTPUT_ROOT.exists():
    raise FileExistsError(f"Choose a fresh OUTPUT_ROOT; this directory already exists: {OUTPUT_ROOT}")
if PREPARE_MEDIA and not MEDIA_ROOT.is_dir():
    raise FileNotFoundError(f"MEDIA_ROOT is not a directory: {MEDIA_ROOT}")
OUTPUT_ROOT.mkdir(parents=True)
images_root_path = str(OUTPUT_ROOT / "posts" / "images")
videos_root_path = str(OUTPUT_ROOT / "posts" / "videos")
for column in ["image_file", "video_file", "media_filename"]:
    df_posts[column] = ""

for index, media in df_media.loc[df_media["selected"]].iterrows():
    if not PREPARE_MEDIA:
        df_media.at[index, "status"] = "metadata only"
        continue
    source = Path(media["local_path"])
    kind = media["kind"]
    directory = Path(images_root_path if kind == "image" else videos_root_path) / media["author"]
    suffix = ".jpg" if kind == "image" else source.suffix.lower()
    destination = directory / f"{media['id']}{suffix}"
    directory.mkdir(parents=True, exist_ok=True)
    try:
        if kind == "image":
            with Image.open(source) as image:
                image.convert("RGB").save(destination, format="JPEG", quality=95)
        else:
            shutil.copy2(source, destination)
    except (OSError, ValueError) as error:
        destination.unlink(missing_ok=True)
        df_media.at[index, "status"] = f"failed: {error}"
        continue
    df_media.at[index, "prepared_path"] = str(destination)
    df_media.at[index, "status"] = "prepared"
    mask = df_posts["id"].eq(media["id"])
    df_posts.loc[mask, f"{kind}_file"] = str(destination)
    if kind == "image":
        df_posts.loc[mask, "media_filename"] = destination.name

for column, path_column in [("has_prepared_image", "image_file"), ("has_prepared_video", "video_file")]:
    df_posts[column] = df_posts[path_column].ne("")

df_posts.to_csv(OUTPUT_ROOT / "posts.csv", index=False)
df_media.to_csv(OUTPUT_ROOT / "media_manifest.csv", index=False)
df_duplicates.to_csv(OUTPUT_ROOT / "duplicate_observations.csv", index=False)
display(df_media.groupby(["kind", "status"]).size().rename("files").reset_index())
print(f"Saved {len(df_posts)} posts to {OUTPUT_ROOT / 'posts.csv'}")
print(f"Posts without a prepared image: {(~df_posts['has_prepared_image']).sum()}")
print(f"Posts without a prepared video: {(~df_posts['has_prepared_video']).sum()}")

7. Continue with OCR and transcription

Open the existing preprocessing notebook. In a new notebook session, run the following setup first, using the same OUTPUT_ROOT as above:

from pathlib import Path
import pandas as pd

OUTPUT_ROOT = Path.home() / "tidaltales-prepared"
df_posts = pd.read_csv(OUTPUT_ROOT / "posts.csv", dtype=str, keep_default_na=False)
images_root_path = str(OUTPUT_ROOT / "posts" / "images")
videos_root_path = str(OUTPUT_ROOT / "posts" / "videos")
audio_save_path = str(OUTPUT_ROOT / "posts" / "audio")

Replace the older notebook’s hard-coded folder assignments (posts/images, posts/videos, and posts/audio) with these paths in every cell that defines them. Set its CSV save paths inside OUTPUT_ROOT as well. With this setup, (author, id) matches the prepared filenames for both OCR and transcription. Keep id as a string when reloading the CSV.

The older stand-alone ocr-notebook.ipynb uses df and image_file: set df = df_posts.loc[df_posts["image_file"].ne("")].copy() first. Its later save path also needs adapting. The older stand-alone Whisper notebook has additional assumptions about audio folders and columns; use the combined preprocessing notebook for this handoff.

When building the Text Master, carry the actual representative image filename through the melt rather than assuming an image exists for every post:

df_long = pd.melt(
    df_posts,
    id_vars=["id", "media_filename"],
    value_vars=["body", "ocr_text", "transcription_text"],
    var_name="Text Type", value_name="Text",
)
df_long["Text Type"] = df_long["Text Type"].map({
    "body": "Caption", "ocr_text": "OCR", "transcription_text": "Transcription",
})
df_long = df_long.rename(columns={"id": "Identifier", "media_filename": "Image"})
df_long["Post Type"] = "Post"
df_long = df_long.loc[df_long["Text"].fillna("").str.strip().ne("")].copy()

Review a sample of OCR and transcripts against the original media before analysis. A blank extracted-text cell can indicate no text, unavailable media, or processing failure; it is not an evaluation result. For galleries or text changing across video frames, plan a separate extraction procedure using the full manifest.