--- license: other task_categories: - text-generation language: - en tags: - screenplay - scriptwriting - causal-lm - gpt2 - fine-tuning - creative-writing pretty_name: Screenplay Corpus — Tokenized (GPT-2) size_categories: - 100K Pre-tokenized screenplay corpus used to train and evaluate the models in the [GPT-2 Screenplay Fine-Tuning Study](https://github.com/raghavnimbalkar1/screenplay-gpt2-finetuning-study). Derived from [Movie-Script-Database](https://github.com/Aveek-Saha/Movie-Script-Database) by Aveek Saha. Provided as tokenized JSON splits ready for direct consumption by a GPT-2 `Trainer` pipeline — no preprocessing required. --- ## Dataset Description This dataset contains approximately **94 million tokens** of professionally formatted screenplay text, pre-tokenized using the GPT-2 tokenizer (`openai-community/gpt2`) and split into training, validation, and test partitions. The raw source corpus was assembled from **2,500+ movie scripts** scraped across 9 industry sources, deduplicated to ~2,400 unique titles, enriched with metadata from three external APIs, cleaned and organized by genre, then tokenized into contiguous 512-token blocks. | Property | Value | |---------------------------|---------------------------------------------------| | **Total Tokens** | ~94 million | | **Source Scripts** | ~2,500 collected → ~2,400 unique (post-dedup) | | **Script Sources** | 9 (IMSDb, DailyScript, Screenplays.io, and others)| | **Genres Covered** | 16+ (Drama, Comedy, Action, Thriller, Horror, ...) | | **Tokenizer** | GPT-2 (`openai-community/gpt2`) | | **Sequence Length** | 512 tokens (contiguous blocks) | | **Train / Val / Test** | 80% / 10% / 10% | | **Language** | English | | **Upstream Source** | [Movie-Script-Database](https://github.com/Aveek-Saha/Movie-Script-Database) (Aveek Saha) | --- ## Data Collection & Processing Pipeline The corpus was assembled using a systematic 6-stage pipeline built on top of the [Movie-Script-Database](https://github.com/Aveek-Saha/Movie-Script-Database) scraping framework. ``` Stage 1: Script Download → 9 sources scraped in parallel via multiprocessing (~4+ hours) Stage 2: Metadata Enrichment → TMDb + IMDb + OMDb API cross-referencing with fuzzy title matching Stage 3: Deduplication → Pairwise fuzzy matching; ~100 cross-source duplicates removed Stage 4: Text Cleaning → Normalization, artifact removal, structure parsing Stage 5: Genre Organization → OMDb genre classification into 16+ genre subfolders Stage 6: Tokenization → GPT-2 tokenizer → 512-token contiguous blocks → train/val/test split ``` ### Stage 1 — Script Sources (9 Total) Scripts were downloaded in parallel from 9 sources, handling HTML, PDF, DOC, and TXT formats: | Source | Format(s) | Notes | |------------------|-------------------|---------------------------------------------------| | **IMSDb** | HTML, PDF | Parsed from `` / `
` tags |
| **Daily Script** | HTML, PDF, TXT    | A–M and N–Z index pages                           |
| **Screenplays.io** | Screenplay docs | —                                                 |
| **ScriptSavant** | —                 | —                                                 |
| **Awesome Film** | —                 | —                                                 |
| **SFY**          | —                 | —                                                 |
| **ScriptSlug**   | —                 | —                                                 |
| **ActorPoint**   | —                 | —                                                 |
| **ScriptPDF**    | PDF               | Specialized PDF-only source                       |

**File format breakdown across all sources:**

| Format | Share | Processing Method          |
|--------|-------|----------------------------|
| HTML   | ~60%  | BeautifulSoup parsing       |
| PDF    | ~25%  | `textract` library          |
| TXT    | ~10%  | Direct UTF-8 read           |
| DOC    | ~5%   | `textract` library          |

### Stage 2 — Metadata Enrichment

Each script was enriched with structured movie metadata by querying three external APIs:

- **TMDb API** — Primary metadata source: title, genres, release year, cast/crew, plot synopsis, ratings
- **IMDbPY** — Secondary validation and IMDb ID cross-referencing
- **OMDb API** — Genre classification and additional movie details

Title matching across sources used fuzzy string matching (`fuzzywuzzy` `token_sort_ratio`) with normalization for articles, Roman numerals, and common screenplay keywords (`draft`, `transcript`, `pilot`).

### Stage 3 — Deduplication

The same script frequently appears on multiple sources. Deduplication was performed by:
1. Generating all pairwise script combinations with `itertools.combinations()`
2. Computing `fuzz.token_set_ratio()` similarity scores
3. Grouping scripts above the similarity threshold
4. Retaining the best copy and tracking all source locations in the metadata `files` array

**Result:** ~2,500 collected → ~2,400 unique scripts.

### Stage 4 — Text Cleaning

Each script was passed through `clean_files.py` with the following normalization operations:

- UTF-8 encoding artifact removal
- Page number removal (formats: `(123)`, `123.`, `(123).`)
- Scene number line removal
- `CONTINUED` / `CONT'D` marker removal
- Special symbol filtering (`•`, `·`, lone special-character lines)
- Excessive whitespace normalization (multiple blank lines collapsed)
- Single-character line removal (except `a` and `i`)
- Minimum script length threshold: **>3,000 bytes**

### Stage 5 — Genre Organization

Scripts were classified into genre subfolders using OMDb genre data. Multi-genre films are assigned to their primary genre. 16+ genres are represented, including: Action, Comedy, Crime, Drama, Horror, Romance, Thriller, Adventure, Sci-Fi, and others.

### Stage 6 — Tokenization & Splitting

Cleaned, genre-organized scripts were tokenized using the GPT-2 tokenizer and split into contiguous 512-token blocks (no padding). The 80/10/10 train/val/test split was performed at the **script level** (not token level) to prevent data leakage across splits.

---

## File Structure

```
dataset/
├── train_tokens.json     # Training split — 80% of scripts
├── val_tokens.json       # Validation split — 10% of scripts, used for eval loss tracking
├── test_tokens.json      # Test split — 10% of scripts, held out entirely
└── stats.json            # Corpus statistics: token counts, split sizes, sequence counts
```

### File Descriptions

**`train_tokens.json`**  
Primary training corpus. The full-parameter cloud model trained on 100% of this split (9,272 steps, 1 full epoch); the LoRA adapter covered approximately 51% (4,700 steps).

**`val_tokens.json`**  
Periodic evaluation split. Used to compute validation loss at checkpoints during both training runs. Validation loss trajectories for both models are documented in their respective model cards.

**`test_tokens.json`**  
Held-out test split. Not seen by either model during any training step. Reserved for post-training evaluation.

**`stats.json`**  
Corpus-level metadata: total token count, per-split sequence counts, tokenizer identifier, and block size configuration. Load this first to inspect dataset dimensions before loading token splits.

---

## Data Format

Each JSON file contains a flat list of token ID sequences. Every sequence is exactly 512 integers — one contiguous block of screenplay text encoded by the GPT-2 tokenizer.

```python
# Structure of stats.json
{
  "total_screenplays": 1090,
  "total_characters": 192537730,
  "total_tokens": 94941785,
  "seq_length": 512,
  "total_sequences": 185433,
  "train_sequences": 148346,
  "val_sequences": 18543,
  "test_sequences": 18544,
  "train_ratio": 0.8,
  "val_ratio": 0.1,
  "test_ratio": 0.1
}
```

---

## Usage

### Loading with Python

```python
import json

# Load stats first to inspect dimensions
with open("stats.json", "r") as f:
    stats = json.load(f)
print(stats)

# Load a split
with open("train_tokens.json", "r") as f:
    train_sequences = json.load(f)

print(f"Training sequences: {len(train_sequences)}")
print(f"Tokens per sequence: {len(train_sequences[0])}")  # 512
```

### Using as a PyTorch Dataset

```python
import json
import torch
from torch.utils.data import Dataset

class ScreenplayTokenDataset(Dataset):
    def __init__(self, json_path):
        with open(json_path, "r") as f:
            self.sequences = json.load(f)

    def __len__(self):
        return len(self.sequences)

    def __getitem__(self, idx):
        ids = torch.tensor(self.sequences[idx], dtype=torch.long)
        return {"input_ids": ids, "labels": ids}  # labels = input_ids for CLM

train_dataset = ScreenplayTokenDataset("train_tokens.json")
val_dataset   = ScreenplayTokenDataset("val_tokens.json")
```

### Decoding a Sample

```python
from transformers import GPT2Tokenizer

tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")

with open("train_tokens.json") as f:
    train_sequences = json.load(f)

sample = train_sequences[0]
print(tokenizer.decode(sample, skip_special_tokens=True))
```

---

## Associated Models

This dataset was used to train two models as part of a cross-platform, dual-architecture comparative fine-tuning study:

| Model | Method | Hardware | Epoch Coverage | Final Eval Loss |
|-------|--------|----------|----------------|-----------------|
| [screenplay-gpt2-full](https://huggingface.co/raghavnimbalkar/gpt2-screenplay-generator) | Full-parameter fine-tune | NVIDIA T4 (Cloud) | 1.0 | **1.3194** |
| [screenplay-gpt2-lora](https://huggingface.co/raghavnimbalkar/gpt2-screenplay-mac-lora) | LoRA / PEFT adapter | Apple Silicon MPS (Local) | 0.51 | 2.4017 |

The same tokenized corpus was used for both runs. The difference in epoch coverage reflects the step budget constraints of local vs. cloud compute, not a difference in dataset preparation.

---

## Source Data, Licensing & Attribution

The raw screenplay text was sourced via the [Movie-Script-Database](https://github.com/Aveek-Saha/Movie-Script-Database) scraping framework (Aveek Saha, 2021), which aggregates publicly available plain-text and HTML screenplay files from 9 online repositories.

**Content filtering:** Scripts shorter than 3,000 bytes were excluded. No filtering for genre, content rating, or theme was applied beyond this threshold. The corpus spans the full tonal and stylistic range of its sources, including material that may be mature, violent, or age-restricted.

- This dataset is provided for **research and educational use only**.
- Individual screenplay texts remain the intellectual property of their respective authors and studios.
- Users are responsible for ensuring compliance with applicable copyright law in their jurisdiction.
- **Not recommended** for production deployment without additional curation, rights clearance, and content review.

---

## Bias, Risks, and Limitations

- The corpus is sourced predominantly from English-language Hollywood and independent American screenplays, reflecting the genre biases, cultural perspectives, and representational patterns of that medium.
- PDF extraction quality varies by source; some scripts may contain OCR artifacts that survived the cleaning pipeline.
- Fuzzy deduplication is threshold-based — similar but distinct films (e.g., remakes, sequels with near-identical titles) may have been incorrectly merged or retained as duplicates.
- Genre assignment is derived from OMDb and is limited to each film's primary genre. Multi-genre distribution is not uniform.
- No toxicity filtering, demographic balancing, or consent audit has been performed.
- This dataset is **not directly compatible** with tokenizers other than GPT-2 (`openai-community/gpt2`). Re-tokenization from raw text is required for other model families.

---

## Technologies Used

| Library        | Version    | Purpose                              |
|----------------|------------|--------------------------------------|
| `beautifulsoup4` | —        | HTML scraping and parsing            |
| `textract`     | 1.6.3      | PDF and DOC text extraction          |
| `fuzzywuzzy`   | 0.18.0     | Fuzzy string matching / deduplication|
| `IMDbPY`       | 2021.4.18  | IMDb metadata API                    |
| `unidecode`    | 1.2.0      | Unicode normalization                |
| `tqdm`         | 4.61.1     | Progress tracking                    |
| `transformers` | —          | GPT-2 tokenizer                      |

---

## Citation

This dataset was built on the Movie-Script-Database collection framework. Please cite the upstream source:

```bibtex
@software{saha2021movie,
  author  = {Saha, Aveek},
  orcid   = {https://orcid.org/0000-0002-6112-3843},
  title   = {Movie Script Database},
  year    = {2021},
  url     = {https://github.com/Aveek-Saha/Movie-Script-Database},
  version = {1.0.0},
  date    = {2021-07-05}
}
```

If referencing the tokenizer:

```bibtex
@article{radford2019language,
  title  = {Language Models are Unsupervised Multitask Learners},
  author = {Radford, Alec and Wu, Jeff and Child, Rewon and Luan, David and Amodei, Dario and Sutskever, Ilya},
  year   = {2019}
}
```

---

## Dataset Card Contact

For questions about tokenization methodology, split construction, or pipeline reproduction, please open an issue in the associated [study repository](https://github.com/raghavnimbalkar1/screenplay-gpt2-finetuning-study).