How to Build a YouTube History Analysis Pipeline
Build a Python pipeline to extract, parse, and analyze your full YouTube viewing history back to 2020 using modern local language models.

Extracting Your YouTube History Archive
Google Takeout remains the only reliable entry point for pulling years of structured platform telemetry. If you want to analyze your viewing habits back to 2020, you cannot rely on the web frontend scraping limiters. You need to request a complete JSON dump through Google Takeout. I waited about four hours for my 1.2 GB archive to generate, and the resulting structure includes a watch-history.json file packed with every video click, timestamp, and channel URL you have touched.
Most developers make the mistake of feeding raw JSON straight into an LLM context window. That approach fails immediately because a multi-year viewing history easily spans hundreds of thousands of lines, blowing past token limits and introducing massive noise from accidental clicks and autoplay loops. You need a data ingestion pipeline that strips out junk metadata, normalizes timestamps, and groups sessions by behavioral intent before any model touches the data.
Let us look at the directory structure we are building for this local pipeline:
youtube_pipeline/
├── data/
│ └── watch-history.json
├── output/
│ └── analyzed_habits.json
├── src/
│ ├── parser.py
│ ├── analyzer.py
│ └── vector_store.py
├── requirements.txt
└── main.py
Before writing code, make sure your environment matches the target specification. You will need Python 3.11 or higher, at least 16GB of RAM if you plan to run local embeddings, and an active API key for your model provider of choice, or a local instance of Llama 4 via Ollama. Create your virtual environment and install the required parsing dependencies using pip:
python3 -m venv venv
source venv/bin/activate
pip install pandas pydantic requests tqdm chromadb
Parsing and Cleaning Raw Google Takeout JSON
Your raw watch-history.json file contains deeply nested dictionaries with redundant fields like header metadata, subheader tags, and HTML artifact strings. We need a reliable Pydantic model to validate each entry and discard incomplete records. If a record lacks a valid video URL or a proper ISO timestamp, it gets dropped silently so it does not pollute our analytical vectors later.
Here is the complete ingestion script in src/parser.py that reads the raw archive, filters out unwanted domains, and structures the records into a clean pandas DataFrame for batch processing:
import json
from datetime import datetime
import pandas as pd
from pydantic import BaseModel, Field
class WatchRecord(BaseModel):
title: str = Field(..., alias='title')
url: str = Field(..., alias='titleUrl')
time: datetime = Field(..., alias='time')
channel: str = Field(default='Unknown')
def clean_youtube_history(file_path: str) -> pd.DataFrame:
with open(file_path, 'r', encoding='utf-8') as f:
raw_data = json.load(f)
parsed_records = []
for entry in raw_data:
try:
# Google Takeout often formats titles like "Watched [Video Title]"
title_text = entry.get('title', '')
if not title_text.startswith('Watched '):
continue
clean_title = title_text.replace('Watched ', '', 1)
subfields = entry.get('subtitles', [])
channel_name = subfields[0].get('name', 'Unknown') if subfields else 'Unknown'
record = {
'title': clean_title,
'url': entry.get('titleUrl', ''),
'time': datetime.fromisoformat(entry.get('time').replace('Z', '+00:00')),
'channel': channel_name
}
parsed_records.append(record)
except (AttributeError, KeyError, ValueError):
continue
df = pd.DataFrame(parsed_records)
df.sort_values(by='time', inplace=True)
df.reset_index(drop=True, inplace=True)
return df
if __name__ == '__main__':
df = clean_youtube_history('data/watch-history.json')
print(f'Successfully parsed {len(df)} viewing events.')
df.to_parquet('output/cleaned_history.parquet')
Run this script inside your terminal using python3 src/parser.py. You should see an output confirming the exact count of valid viewing events extracted from your multi-year archive. Storing the output as a Parquet file rather than CSV drastically speeds up downstream loading times when working with large datasets.
How Do We Group Viewing Sessions Using Temporal Clustering?
Viewing a single technical tutorial is very different from falling into a three-hour rabbit hole of music videos at 2:00 AM. To extract meaningful insights about your personal evolution since 2020, we need to segment your watch history into coherent behavioral sessions based on time gaps.
We define a session break as any gap in viewing timestamps exceeding 30 minutes. By applying this sliding delta across our sorted DataFrame, we can aggregate individual video clicks into distinct watch sessions complete with duration bounds and topic concentrations.
Implement the clustering logic in src/analyzer.py:
import pandas as pd
from datetime import timedelta
def segment_sessions(df: pd.DataFrame, gap_minutes: int = 30) -> pd.DataFrame:
df['time_diff'] = df['time'].diff()
session_gap = timedelta(minutes=gap_minutes)
# Create a boolean mask where True indicates a new session
df['new_session'] = df['time_diff'] > session_gap
df['session_id'] = df['new_session'].cumsum()
session_summary = df.groupby('session_id').agg(
start_time=('time', 'min'),
end_time=('time', 'max'),
video_count=('title', 'count'),
channels=('channel', lambda x: list(x.unique())),
titles=('title', lambda x: list(x))
)
session_summary['duration_minutes'] = (
session_summary['end_time'] - session_summary['start_time']
).dt.total_seconds() / 60
return session_summary
if __name__ == '__main__':
df = pd.read_parquet('output/cleaned_history.parquet')
sessions = segment_sessions(df)
print(f'Identified {len(sessions)} distinct viewing sessions.')
sessions.to_parquet('output/sessions.parquet')
Once grouped, you can query specific behavioral slices. For instance, finding all sessions longer than 90 minutes that occurred between midnight and 5:00 AM reveals your late-night research spirals or entertainment binges over the past several years.
Troubleshooting Common Ingestion Failures
Processing years of platform telemetry almost always triggers edge cases. Here are three errors you will likely encounter and how to fix them immediately in your local environment.
First, if your parser crashes with a KeyError: 'titleUrl', Google Takeout has altered its schema for deleted videos or external ad impressions. Fix this by wrapping key lookups with safe dictionary gets and filtering out entries where titleUrl is null:
# Fix for missing titleUrl fields
if not entry.get('titleUrl'):
continue
Second, encountering a ValueError: Invalid isoformat string means Google changed its UTC timezone formatting string across different year exports. Normalize all timestamp strings before parsing by substituting timezone indicators explicitly:
# Fix for malformed ISO timestamps
raw_time = entry.get('time', '').replace('Z', '+00:00')
if '.' in raw_time:
# Truncate microseconds if they exceed standard 6 digits
base, tz = raw_time.split('+')
raw_time = base[:19] + '+' + tz
Third, running out of memory during parquet writes or pandas groupbys on lower-spec machines requires chunked processing. Read your large JSON files using an iterative generator approach rather than loading everything into RAM at once.
Production Considerations and Rate Limiting
If you decide to feed these cleaned sessions into an LLM for automated categorization or sentiment analysis of your viewing trajectory, you must respect provider rate limits. Sending 5,000 individual session summaries to an API endpoint will trigger HTTP 429 errors instantly.
Implement strict batching, exponential backoff, and local caching using SQLite or ChromaDB. Never send raw PII or exact user account identifiers to third-party endpoints. Scrub channel names and video titles of any personal tokens if you are pushing data outside your local machine. Also, set environment variables securely using a .env file loaded via python-dotenv rather than hardcoding keys into your scripts.
What to Build Next
Once your local pipeline is running smoothly, you can extend the architecture into more advanced telemetry workflows. Try integrating a local vector store like ChromaDB with your session data to perform semantic search over your past viewing history. You can ask queries like "When did I stop watching hardware teardown videos and start focusing on AI agent architectures?" and get precise temporal answers based entirely on your personal dataset.
Bottom Line
Parsing your multi-year YouTube history requires stripping out platform noise and structuring raw JSON into clean temporal sessions before any model analysis begins. Build the local ingestion pipeline outlined here, keep your dependencies updated, and take full control of your digital footprint.
Related Analyses
More in Tutorials →
Build a Custom Cyber Coach with Python and Dot AI
Step-by-step tutorial on building a secure AI cyber coach for small businesses using Python, local vector search, and dot framework integration.

How to Generate a 3D Game Engine with AI
I tested single prompt 3D game engine generation using LLMs. Here is how to build, run, and fix an AI generated rendering pipeline from scratch.

Run NVIDIA Cosmos 3 Locally With Diffusers
Step-by-step technical guide on running NVIDIA Cosmos 3 locally on your hardware using Hugging Face Diffusers, including full code blocks and