🎭 Emotion Analyzer¶

Detect human facial expressions in a YouTube video using DeepFace for fast emotion classification and Claude Vision AI to explain why each face shows that specific feeling.

Pipeline¶

  1. Download a YouTube video with yt-dlp
  2. Sample one frame every N seconds with OpenCV
  3. Detect faces & classify emotions with DeepFace
  4. Use Claude Vision to generate a per-face natural-language explanation citing specific facial muscle cues
  5. Render a gallery of the most expressive moments

Video analyzed: https://www.youtube.com/watch?v=y1PruACVorM

In [1]:
# ── Install required packages ─────────────────────────────────────────────────
import subprocess, sys

PACKAGES = ["deepface", "tf-keras", "tqdm", "pillow"]

for pkg in PACKAGES:
    result = subprocess.run(
        [sys.executable, "-m", "pip", "install", pkg,
         "--break-system-packages", "-q"],
        capture_output=True, text=True,
    )
    status = "\u2713" if result.returncode == 0 else "\u2717"
    print(f"{status} {pkg}")
✓ deepface
✓ tf-keras
✓ tqdm
✓ pillow
In [2]:
import os, sys

# ── TF env vars — must be set before any TF-related import ───────────────────
os.environ["TF_CPP_MIN_LOG_LEVEL"]  = "3"
os.environ["CUDA_VISIBLE_DEVICES"]  = "-1"
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"

import cv2, base64, json, time, warnings, io
from pathlib import Path
from collections import Counter

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

import yt_dlp
import anthropic
from PIL import Image

warnings.filterwarnings("ignore")

# ── DeepFace — import with fd-level stderr redirect ──────────────────────────
# cudart_stub.cc writes directly to OS file descriptor 2, bypassing Python's
# sys.stderr and all Python-level logging controls.  The only reliable fix is
# to point fd 2 at /dev/null for the duration of the import, then restore it.
_saved_fd2  = os.dup(2)
_devnull_fd = os.open(os.devnull, os.O_WRONLY)
os.dup2(_devnull_fd, 2)
os.close(_devnull_fd)

try:
    from deepface import DeepFace
    DEEPFACE_AVAILABLE = True
except Exception as _e:
    DEEPFACE_AVAILABLE = False
    _deepface_err = str(_e)
finally:
    os.dup2(_saved_fd2, 2)   # always restore stderr
    os.close(_saved_fd2)

if DEEPFACE_AVAILABLE:
    print("✓ DeepFace loaded")
else:
    print(f"⚠ DeepFace unavailable ({_deepface_err}) — will use Claude Vision instead")

# ── Anthropic client ──────────────────────────────────────────────────────────
API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
if not API_KEY:
    raise EnvironmentError(
        "ANTHROPIC_API_KEY is not set.\n"
        "Run: export ANTHROPIC_API_KEY='sk-ant-...' before launching Jupyter."
    )
client = anthropic.Anthropic(api_key=API_KEY)
print("✓ Anthropic client ready")
✓ DeepFace loaded
✓ Anthropic client ready
In [3]:
# ── Configuration — edit these as needed ──────────────────────────────────────

VIDEO_URL = "https://www.youtube.com/watch?v=y1PruACVorM"

OUTPUT_DIR       = Path("emotion_analysis")
VIDEO_PATH       = OUTPUT_DIR / "video.mp4"
FACES_DIR        = OUTPUT_DIR / "faces"
FRAMES_DIR       = OUTPUT_DIR / "frames"
CARDS_DIR        = OUTPUT_DIR / "outputs"
FRAMES_MANIFEST  = FRAMES_DIR / "manifest.json"   # frame extraction cache
DETECTIONS_CACHE = OUTPUT_DIR / "detections.json"  # emotion analysis cache

for d in (OUTPUT_DIR, FACES_DIR, FRAMES_DIR, CARDS_DIR):
    d.mkdir(exist_ok=True)

SAMPLE_EVERY_N_SECONDS = 3   # analyze one frame every N seconds
MAX_RESULTS            = 8   # max emotional moments to display

# To force a full rerun delete these files:
#   emotion_analysis/frames/manifest.json  → re-extracts frames from video
#   emotion_analysis/detections.json       → re-runs emotion detection + explanations

EMOTION_COLORS = {
    "happy":   "#FFD700",
    "sad":     "#5B8DD9",
    "surprise":"#FF69B4",
    "fear":    "#9B59B6",
    "angry":   "#E74C3C",
    "disgust": "#2ECC71",
    "neutral": "#95A5A6",
}

EMOTION_EMOJI = {
    "happy": "\U0001f60a", "sad": "\U0001f622", "surprise": "\U0001f632",
    "fear":  "\U0001f628", "angry": "\U0001f621",
    "disgust": "\U0001f922", "neutral": "\U0001f610",
}

print(f"Output    : {OUTPUT_DIR.resolve()}")
print(f"Cards dir : {CARDS_DIR.resolve()}")
print(f"Frame cache: {FRAMES_MANIFEST}")
print(f"Det. cache : {DETECTIONS_CACHE}")
Output    : /home/patito/Documents/Image_analytics/emotion_analysis
Cards dir : /home/patito/Documents/Image_analytics/emotion_analysis/outputs
Frame cache: emotion_analysis/frames/manifest.json
Det. cache : emotion_analysis/detections.json
In [4]:
def download_video(url: str, output: Path) -> None:
    """Download a YouTube video at ≤480p, forcing H.264 so OpenCV can decode it."""
    if output.exists() and output.stat().st_size > 100_000:
        print(f"✓ Already downloaded: {output.name}")
        return

    ydl_opts = {
        "format": (
            # Prefer H.264 (avc1) — AV1 is not decodable by OpenCV without HW support
            "bestvideo[height<=480][vcodec^=avc][ext=mp4]+bestaudio[ext=m4a]"
            "/bestvideo[height<=480][vcodec!=av01][ext=mp4]+bestaudio[ext=m4a]"
            "/18"  # fallback: format 18 is a reliable 360p H.264+AAC single-file mux
        ),
        "outtmpl": str(output.with_suffix("")),
        "merge_output_format": "mp4",
        "quiet": True,
        "no_warnings": True,
    }
    print(f"Downloading: {url}")
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=True)

    mins, secs = divmod(int(info.get("duration", 0)), 60)
    print(f"✓ '{info.get('title','?')}' ({mins}m{secs:02d}s)")


download_video(VIDEO_URL, VIDEO_PATH)
✓ Already downloaded: video.mp4
In [5]:
def extract_sample_frames(video_path: Path, every_n_sec: int = 3) -> list:
    """
    Return one frame dict per N seconds.
    Saves frames as JPEGs + a manifest.json on first run;
    reloads from disk on subsequent runs (skips video decoding entirely).
    Delete manifest.json to force re-extraction.
    """
    # ── Cache hit ─────────────────────────────────────────────────────────────
    if FRAMES_MANIFEST.exists():
        with open(FRAMES_MANIFEST) as f:
            manifest = json.load(f)

        frames = []
        for entry in manifest:
            p = OUTPUT_DIR / entry["path"]
            if not p.exists():
                print(f"⚠ Missing cached frame {p.name} — rebuilding cache…")
                frames = []
                break
            frames.append({
                "frame":     np.array(Image.open(p)),
                "timestamp": entry["timestamp"],
                "frame_idx": entry["frame_idx"],
            })
        else:
            print(f"✓ Loaded {len(frames)} frames from cache  (delete {FRAMES_MANIFEST.name} to re-extract)")
            return frames

    # ── Extract from video ────────────────────────────────────────────────────
    cap = cv2.VideoCapture(str(video_path))
    if not cap.isOpened():
        raise RuntimeError(f"Cannot open: {video_path}")

    fps          = cap.get(cv2.CAP_PROP_FPS) or 25.0
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration     = total_frames / fps
    step         = max(1, int(fps * every_n_sec))

    print(f"Video: {total_frames} frames @ {fps:.1f} fps → {duration:.0f}s")
    print(f"Sampling every {every_n_sec}s → ~{total_frames // step} frames to extract")

    frames, manifest, idx = [], [], 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        if idx % step == 0:
            ts  = idx / fps
            rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            rel = f"frames/frame_{idx:06d}_t{ts:.1f}s.jpg"
            Image.fromarray(rgb).save(OUTPUT_DIR / rel, quality=90)
            frames.append({"frame": rgb, "timestamp": ts, "frame_idx": idx})
            manifest.append({"frame_idx": idx, "timestamp": ts, "path": rel})
        idx += 1

    cap.release()
    with open(FRAMES_MANIFEST, "w") as f:
        json.dump(manifest, f, indent=2)
    print(f"✓ Extracted {len(frames)} frames → cached to {FRAMES_DIR.name}/")
    return frames


sample_frames = extract_sample_frames(VIDEO_PATH, SAMPLE_EVERY_N_SECONDS)
✓ Loaded 103 frames from cache  (delete manifest.json to re-extract)
In [6]:
# ── Shared helpers ────────────────────────────────────────────────────────────

def img_to_b64(arr: np.ndarray) -> str:
    """RGB numpy array \u2192 base-64 JPEG string."""
    buf = io.BytesIO()
    Image.fromarray(arr).save(buf, format="JPEG", quality=85)
    return base64.standard_b64encode(buf.getvalue()).decode()


def normalize_scores(scores: dict) -> dict:
    """Ensure emotion scores are in the 0-100 range."""
    mx = max(scores.values(), default=1)
    return {k: v * 100 for k, v in scores.items()} if mx <= 1.0 else dict(scores)


# ── DeepFace emotion analysis ─────────────────────────────────────────────────

def deepface_analyze(frame_rgb: np.ndarray) -> list:
    """
    Detect ALL faces in the frame and return one result dict per face.
    Each dict: {dominant, scores, bbox, face_crop}.
    Returns [] on failure.
    """
    try:
        results = DeepFace.analyze(
            frame_rgb,
            actions=["emotion"],
            enforce_detection=True,
            detector_backend="opencv",
            silent=True,
        )
        if not isinstance(results, list):
            results = [results]

        hits = []
        for res in results:
            region = res.get("region", {})
            x = region.get("x", 0)
            y = region.get("y", 0)
            w = region.get("w", frame_rgb.shape[1])
            h = region.get("h", frame_rgb.shape[0])

            # Pad the crop by 20 %
            pad_x = int(w * 0.20)
            pad_y = int(h * 0.20)
            x1 = max(0, x - pad_x)
            y1 = max(0, y - pad_y)
            x2 = min(frame_rgb.shape[1], x + w + pad_x)
            y2 = min(frame_rgb.shape[0], y + h + pad_y)
            face_crop = frame_rgb[y1:y2, x1:x2]

            if face_crop.size == 0 or min(face_crop.shape[:2]) < 40:
                continue

            hits.append({
                "dominant":  res["dominant_emotion"],
                "scores":    normalize_scores(res["emotion"]),
                "bbox":      (x, y, w, h),
                "face_crop": face_crop,
                "source":    "deepface",
                "explanation": "",
            })
        return hits
    except Exception:
        return []


# ── Claude Vision — detect & explain ─────────────────────────────────────────

_DETECT_PROMPT = """\
You are an expert in facial expression analysis.
Look at this face crop and respond with ONLY a JSON object (no prose, no markdown fences).

Schema:
{{
  "dominant_emotion": "<happy|sad|surprise|fear|angry|disgust|neutral>",
  "scores": {{"happy":0,"sad":0,"surprise":0,"fear":0,"angry":0,"disgust":0,"neutral":0}},
  "explanation": "<2-3 sentences citing specific facial muscle cues>"
}}

scores must be 0-100 and sum to ~100."""

_EXPLAIN_PROMPT = """\
This face has been classified as expressing **{emotion}** (top scores: {scores}).

Write 2-3 sentences explaining which specific facial features you observe that justify this classification.
Cite concrete muscle / action-unit indicators (e.g., "zygomaticus major raises lip corners",
"orbicularis oculi contracts to produce crow's feet", "corrugator supercilii furrows the brow").
Be precise and educational — this explanation will appear in a public portfolio."""


def claude_detect(face_rgb: np.ndarray) -> dict | None:
    """Use Claude Vision to detect emotion + generate first explanation."""
    try:
        msg = client.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=450,
            messages=[{
                "role": "user",
                "content": [
                    {"type": "image",
                     "source": {"type": "base64",
                                "media_type": "image/jpeg",
                                "data": img_to_b64(face_rgb)}},
                    {"type": "text", "text": _DETECT_PROMPT},
                ],
            }],
        )
        raw = msg.content[0].text.strip()
        # Strip markdown fences if present
        if raw.startswith("```"):
            raw = raw.split("```")[1]
            if raw.startswith("json"):
                raw = raw[4:]
        data = json.loads(raw)
        return {
            "dominant":    data["dominant_emotion"],
            "scores":      normalize_scores(data["scores"]),
            "explanation": data.get("explanation", ""),
            "face_crop":   face_rgb,
            "source":      "claude",
        }
    except Exception as e:
        print(f"      [claude_detect error: {e}]")
        return None


def claude_explain(face_rgb: np.ndarray, emotion: str, scores: dict) -> str:
    """Ask Claude to narrate the facial cues for an already-classified face."""
    top3 = ", ".join(
        f"{k} {v:.0f}%"
        for k, v in sorted(scores.items(), key=lambda x: -x[1])[:3]
    )
    msg = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=300,
        messages=[{
            "role": "user",
            "content": [
                {"type": "image",
                 "source": {"type": "base64",
                            "media_type": "image/jpeg",
                            "data": img_to_b64(face_rgb)}},
                {"type": "text",
                 "text": _EXPLAIN_PROMPT.format(emotion=emotion, scores=top3)},
            ],
        }],
    )
    return msg.content[0].text.strip()


print("\u2713 Analysis functions ready")
print(f"  Primary detector : {'DeepFace' if DEEPFACE_AVAILABLE else 'Claude Vision'}")
print( "  Explanation model: Claude Vision (claude-sonnet-4-6)")
✓ Analysis functions ready
  Primary detector : DeepFace
  Explanation model: Claude Vision (claude-sonnet-4-6)
In [7]:
# ── Cache helpers ─────────────────────────────────────────────────────────────

def _det_paths(i: int) -> tuple[Path, Path]:
    return (
        FACES_DIR / f"det_{i:02d}_face.jpg",
        FACES_DIR / f"det_{i:02d}_frame.jpg",
    )


def save_detections(detections: list) -> None:
    """Write detections to detections.json; numpy arrays saved as JPEGs."""
    records = []
    for i, det in enumerate(detections):
        face_p, frame_p = _det_paths(i)
        Image.fromarray(det["face_crop"]).save(face_p, quality=92)
        Image.fromarray(det["frame"]).save(frame_p, quality=88)
        records.append({
            "timestamp":        float(det["timestamp"]),
            "dominant_emotion": str(det["dominant_emotion"]),
            "emotion_scores":   {k: float(v) for k, v in det["emotion_scores"].items()},
            "expressiveness":   float(det["expressiveness"]),
            "explanation":      det.get("explanation", ""),
            "source":           det.get("source", "unknown"),
            "bbox":             [int(v) for v in det["bbox"]] if det.get("bbox") else None,
            "face_crop_path":   str(face_p.relative_to(OUTPUT_DIR)),
            "frame_path":       str(frame_p.relative_to(OUTPUT_DIR)),
        })
    with open(DETECTIONS_CACHE, "w") as f:
        json.dump(records, f, indent=2)
    print(f"✓ Saved {len(records)} detections → {DETECTIONS_CACHE.name}")


def load_detections() -> list:
    """Read detections.json and reload image arrays from disk."""
    with open(DETECTIONS_CACHE) as f:
        records = json.load(f)
    result = []
    for r in records:
        result.append({
            **r,
            "face_crop": np.array(Image.open(OUTPUT_DIR / r["face_crop_path"])),
            "frame":     np.array(Image.open(OUTPUT_DIR / r["frame_path"])),
            "bbox":      tuple(r["bbox"]) if r.get("bbox") else None,
        })
    return result


# ── Main pipeline ─────────────────────────────────────────────────────────────

def process_frames(frames: list, max_results: int = 8) -> list:
    """
    Detect faces + emotions across all sampled frames.
    Results cached to detections.json — delete it to reprocess.
    """
    if DETECTIONS_CACHE.exists():
        dets = load_detections()
        print(f"✓ Loaded {len(dets)} detections from cache  (delete {DETECTIONS_CACHE.name} to reprocess)")
        return dets

    all_hits: list[dict] = []

    for i, fd in enumerate(frames):
        frame = fd["frame"]
        ts    = fd["timestamp"]

        if (i + 1) % 15 == 0 or i == 0:
            pct = 100 * (i + 1) / len(frames)
            print(f"  [{i+1:>3}/{len(frames)}]  {pct:3.0f}%  —  {len(all_hits)} faces found so far")

        hits = []
        if DEEPFACE_AVAILABLE:
            hits = deepface_analyze(frame)

        if not hits:
            h_f, w_f = frame.shape[:2]
            margin   = int(min(h_f, w_f) * 0.08)
            crop     = frame[margin:h_f - margin, margin:w_f - margin]
            res = claude_detect(crop)
            if res:
                hits = [res]
            time.sleep(0.1)

        for hit in hits:
            scores         = hit["scores"]
            dominant       = hit["dominant"]
            expressiveness = 1.0 - scores.get("neutral", 0) / 100

            face_crop = hit.get("face_crop")
            if face_crop is None:
                h_f, w_f = frame.shape[:2]
                pad       = int(min(h_f, w_f) * 0.08)
                face_crop = frame[pad:h_f - pad, pad:w_f - pad]

            all_hits.append({
                "frame":            frame,
                "face_crop":        face_crop,
                "timestamp":        ts,
                "dominant_emotion": dominant,
                "emotion_scores":   scores,
                "expressiveness":   expressiveness,
                "explanation":      hit.get("explanation", ""),
                "source":           hit.get("source", "unknown"),
                "bbox":             hit.get("bbox"),
            })

    print(f"\n✓ {len(all_hits)} face detections total")

    by_emotion: dict[str, dict] = {}
    for hit in all_hits:
        em = hit["dominant_emotion"]
        if em not in by_emotion or hit["expressiveness"] > by_emotion[em]["expressiveness"]:
            by_emotion[em] = hit

    selected     = list(by_emotion.values())
    selected_ids = {id(h) for h in selected}
    extra = sorted(
        [h for h in all_hits if id(h) not in selected_ids],
        key=lambda x: -x["expressiveness"],
    )
    selected.extend(extra[: max(0, max_results - len(selected))])
    selected = sorted(selected[:max_results], key=lambda x: x["timestamp"])

    save_detections(selected)
    return selected


print("Running analysis pipeline…\n")
detections = process_frames(sample_frames, MAX_RESULTS)
print(f"\n✓ {len(detections)} emotional moments selected")
Running analysis pipeline…

✓ Loaded 8 detections from cache  (delete detections.json to reprocess)

✓ 8 emotional moments selected
In [8]:
# ── Enrich detections with Claude explanations ────────────────────────────────
# Explanations already in cache → nothing to do.
# Partial cache (interrupted run) → only fetches the missing ones, then re-saves.

missing = [i for i, d in enumerate(detections) if not d.get("explanation")]

if not missing:
    print("✓ All explanations already cached — skipping API calls")
else:
    print(f"Fetching {len(missing)} explanation(s) from Claude Vision…\n")

    for i, det in enumerate(detections):
        em    = det["dominant_emotion"]
        ts    = det["timestamp"]
        emoji = EMOTION_EMOJI.get(em, "?")

        if det.get("explanation"):
            print(f"  [{i+1}/{len(detections)}] {emoji} {em:8s} @ {ts:5.1f}s  ✔ cached")
            continue

        print(f"  [{i+1}/{len(detections)}] {emoji} {em:8s} @ {ts:5.1f}s  …", end="", flush=True)
        try:
            det["explanation"] = claude_explain(
                det["face_crop"], em, det["emotion_scores"]
            )
            print(" ✓")
        except Exception as exc:
            det["explanation"] = f"(Explanation unavailable: {exc})"
            print(f" ✗ {exc}")
        time.sleep(0.3)

    # Re-save so explanations are persisted for next run
    save_detections(detections)
    print("\n✓ Explanations saved to cache")
✓ All explanations already cached — skipping API calls
In [9]:
def fmt_ts(s: float) -> str:
    m, sec = divmod(int(s), 60)
    return f"{m}:{sec:02d}"


def draw_bbox_on_frame(frame: np.ndarray, bbox: tuple | None) -> np.ndarray:
    """Return a copy of frame with the face bounding box drawn."""
    out = frame.copy()
    if bbox:
        x, y, w, h = bbox
        cv2.rectangle(out, (x, y), (x + w, y + h), (255, 220, 0), 3)
    return out


def display_gallery(detections: list) -> None:
    """Render one card per emotional moment and save PNGs."""

    for idx, det in enumerate(detections):
        emotion = det["dominant_emotion"]
        color   = EMOTION_COLORS.get(emotion, "#888")
        emoji   = EMOTION_EMOJI.get(emotion, "?")
        scores  = det["emotion_scores"]
        ts      = det["timestamp"]
        face    = det["face_crop"]
        frame   = det["frame"]
        bbox    = det.get("bbox")

        annotated_frame = draw_bbox_on_frame(frame, bbox)

        fig = plt.figure(figsize=(20, 5.5), facecolor="#12121f")
        gs  = gridspec.GridSpec(
            1, 4, figure=fig,
            width_ratios=[1.5, 1.0, 1.3, 2.1],
            wspace=0.22, left=0.02, right=0.98,
        )

        # Panel A — full frame with bbox ──────────────────────────────────────
        ax_frame = fig.add_subplot(gs[0])
        ax_frame.imshow(annotated_frame)
        ax_frame.set_title(
            f"⏱ {fmt_ts(ts)}  —  face #{idx+1}",
            color="#aaaaaa", fontsize=10, pad=6,
        )
        ax_frame.axis("off")

        # Panel B — face crop ─────────────────────────────────────────────────
        ax_face = fig.add_subplot(gs[1])
        ax_face.imshow(face)
        ax_face.set_title(
            f"{emoji}  {emotion.upper()}",
            color=color, fontsize=14, fontweight="bold", pad=10,
        )
        ax_face.axis("off")
        for sp in ax_face.spines.values():
            sp.set_edgecolor(color)
            sp.set_linewidth(3)
            sp.set_visible(True)

        # Panel C — emotion score bars ────────────────────────────────────────
        ax_bars = fig.add_subplot(gs[2])
        ax_bars.set_facecolor("#1e1e30")

        order   = sorted(scores.items(), key=lambda x: -x[1])
        labels  = [e for e, _ in order]
        values  = [v for _, v in order]
        bcolors = [EMOTION_COLORS.get(e, "#888") for e in labels]

        bars = ax_bars.barh(labels, values, color=bcolors, alpha=0.85, height=0.6)
        ax_bars.set_xlim(0, 105)
        ax_bars.set_xlabel("Confidence (%)", color="#aaa", fontsize=9)
        ax_bars.set_title("Emotion Scores", color="white",
                          fontsize=11, fontweight="bold")
        ax_bars.tick_params(colors="white", labelsize=9)
        for sp in ["top", "right"]:
            ax_bars.spines[sp].set_visible(False)
        for sp in ["bottom", "left"]:
            ax_bars.spines[sp].set_color("#444")
        for bar, val in zip(bars, values):
            ax_bars.text(
                bar.get_width() + 1.5,
                bar.get_y() + bar.get_height() / 2,
                f"{val:.1f}%",
                va="center", color="white", fontsize=8,
            )

        # Panel D — Claude explanation ─────────────────────────────────────────
        ax_text = fig.add_subplot(gs[3])
        ax_text.set_facecolor("#1e1e30")
        ax_text.axis("off")

        ax_text.text(
            0.04, 0.94,
            "Claude Vision Analysis",
            transform=ax_text.transAxes,
            fontsize=12, fontweight="bold", color=color, va="top",
        )

        # Word-wrap the explanation manually for matplotlib
        import textwrap
        wrapped = "\n".join(textwrap.wrap(det["explanation"], width=72))
        ax_text.text(
            0.04, 0.80,
            wrapped,
            transform=ax_text.transAxes,
            fontsize=10, color="#e0e0e0", va="top",
            multialignment="left", linespacing=1.55,
            family="monospace",
        )

        source_label = (
            f"Detection: {det.get('source','?').upper()}  •  "
            f"timestamp {fmt_ts(ts)}  •  "
            f"face {idx+1}/{len(detections)}"
        )
        ax_text.text(
            0.04, 0.03, source_label,
            transform=ax_text.transAxes,
            fontsize=8, color="#666", va="bottom", style="italic",
        )

        save_path = CARDS_DIR / f"card_{idx+1:02d}_{emotion}.png"
        plt.savefig(save_path, dpi=130, bbox_inches="tight",
                    facecolor="#12121f")
        plt.show()
        plt.close()

        # Also save the face crop alone
        Image.fromarray(face).save(FACES_DIR / f"face_{idx+1:02d}_{emotion}.jpg")


display_gallery(detections)
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
In [10]:
def show_summary(detections: list) -> None:
    """Emotion distribution pie chart + timeline scatter plot."""
    if not detections:
        print("No detections to summarise.")
        return

    counts = Counter(d["dominant_emotion"] for d in detections)

    fig, axes = plt.subplots(1, 2, figsize=(15, 6.5), facecolor="#12121f")

    # ── Pie chart ─────────────────────────────────────────────────────────────
    ax_pie = axes[0]
    ax_pie.set_facecolor("#1e1e30")

    em_list  = list(counts.keys())
    vals     = list(counts.values())
    pie_cols = [EMOTION_COLORS.get(e, "#888") for e in em_list]
    labels   = [f"{EMOTION_EMOJI.get(e,'?')} {e}\n({v} moment{'s' if v>1 else ''})"
                for e, v in zip(em_list, vals)]

    wedges, texts, autotexts = ax_pie.pie(
        vals, labels=labels, colors=pie_cols,
        autopct="%1.0f%%", startangle=140,
        textprops={"color": "white", "fontsize": 11},
        wedgeprops={"linewidth": 1.5, "edgecolor": "#12121f"},
    )
    for at in autotexts:
        at.set_fontweight("bold")
    ax_pie.set_title(
        "Emotion Distribution\n(selected moments)",
        color="white", fontsize=14, fontweight="bold", pad=16,
    )

    # ── Timeline scatter ──────────────────────────────────────────────────────
    ax_tl = axes[1]
    ax_tl.set_facecolor("#1e1e30")

    all_em = sorted(EMOTION_COLORS.keys())
    for det in detections:
        em  = det["dominant_emotion"]
        ts  = det["timestamp"]
        c   = EMOTION_COLORS.get(em, "#888")
        yi  = all_em.index(em) if em in all_em else 0
        ax_tl.scatter(ts, yi, c=c, s=260, zorder=5,
                      edgecolors="white", linewidth=1.8)
        ax_tl.text(ts, yi + 0.22, fmt_ts(ts),
                   ha="center", va="bottom", color="#ccc", fontsize=7.5)

    ax_tl.set_yticks(range(len(all_em)))
    ax_tl.set_yticklabels(
        [f"{EMOTION_EMOJI.get(e,'?')} {e}" for e in all_em],
        color="white", fontsize=10.5,
    )
    ax_tl.set_xlabel("Video time (seconds)", color="#aaa", fontsize=10)
    ax_tl.set_title("Emotional Moments — Timeline",
                    color="white", fontsize=14, fontweight="bold")
    ax_tl.tick_params(axis="x", colors="#aaa")
    for sp in ["top", "right"]:
        ax_tl.spines[sp].set_visible(False)
    for sp in ["bottom", "left"]:
        ax_tl.spines[sp].set_color("#444")
    ax_tl.grid(axis="x", color="#333", linestyle="--", alpha=0.5)
    ax_tl.set_ylim(-0.6, len(all_em) - 0.4)

    plt.tight_layout(pad=2.5)
    plt.savefig(CARDS_DIR / "summary.png", dpi=130,
                bbox_inches="tight", facecolor="#12121f")
    plt.show()
    plt.close()

    # ── Text summary ──────────────────────────────────────────────────────────
    print("\n" + "=" * 52)
    print("  EMOTION ANALYSIS SUMMARY")
    print("=" * 52)
    for em, cnt in counts.most_common():
        bar = "█" * cnt
        print(f"  {EMOTION_EMOJI.get(em,'?')} {em:<10} {bar}  ({cnt})")
    print("=" * 52)
    print(f"\n✓ Cards saved to: {CARDS_DIR.resolve()}")


show_summary(detections)
No description has been provided for this image
====================================================
  EMOTION ANALYSIS SUMMARY
====================================================
  😊 happy      ████  (4)
  😢 sad        █  (1)
  😡 angry      █  (1)
  😐 neutral    █  (1)
  😨 fear       █  (1)
====================================================

✓ Cards saved to: /home/patito/Documents/Image_analytics/emotion_analysis/outputs