terminal-cli-commands-dataset / build_cli_only.py
kipasyangin5's picture
Add CLI dataset build Python script
205bae1 verified
Raw
History Blame Contribute Delete
12 kB
"""
Pure Linux Terminal & CLI Commands Dataset Generator & HuggingFace Uploader
Generates 100,000 pure Linux CLI command scenarios, shell interactions, and Q&A pairs.
"""
import os
import json
import gzip
import shutil
import random
from huggingface_hub import HfApi
print("=== Building Pure Linux Terminal & CLI Commands Dataset ===")
COMMAND_TEMPLATES = [
("How do I navigate up one directory?", "cd .."),
("How do I go to the home directory?", "cd ~"),
("How do I check my current directory path?", "pwd"),
("How do I list all files including hidden files?", "ls -la"),
("How do I list files with human readable file sizes?", "ls -lh"),
("How do I create a nested directory structure?", "mkdir -p path/to/nested/directory"),
("How do I print directory tree structure?", "tree -L 2"),
("How do I copy a directory recursively?", "cp -r source_dir/ target_dir/"),
("How do I move or rename a file?", "mv old_filename.txt new_filename.txt"),
("How do I force remove a folder and all contents?", "rm -rf target_folder/"),
("How do I create an empty file?", "touch index.js"),
("How do I inspect the first 20 lines of a file?", "head -n 20 logfile.log"),
("How do I monitor a log file in real-time?", "tail -f /var/log/syslog"),
("How do I count lines in a text file?", "wc -l dataset.txt"),
("How do I recursively search for text in files?", 'grep -rn "search_term" .'),
("How do I find all python files in the current folder?", 'find . -type f -name "*.py"'),
("How do I find files larger than 100MB?", "find / -size +100M 2>/dev/null"),
("How do I sort lines and remove duplicates?", "sort input.txt | uniq -c"),
("How do I replace text in a file inline?", "sed -i 's/old_text/new_text/g' config.yaml"),
("How do I make a shell script executable?", "chmod +x script.sh"),
("How do I give full read/write/execute permissions to owner?", "chmod 755 binary_file"),
("How do I change owner of a folder recursively?", "chown -R www-data:www-data /var/www/html"),
("How do I list running processes matching python?", "ps aux | grep python"),
("How do I kill a process by process ID?", "kill -9 12345"),
("How do I check system RAM usage?", "free -h"),
("How do I check disk space usage in human readable format?", "df -h"),
("How do I check disk usage of current directories?", "du -sh * | sort -hr"),
("How do I test network connectivity to a host?", "ping -c 4 google.com"),
("How do I download a file silently with curl?", "curl -sSL https://example.com/file.tar.gz -o file.tar.gz"),
("How do I download a file using wget?", "wget -q https://example.com/data.json"),
("How do I SSH into a remote server with custom port?", "ssh -p 2222 user@remote-host.com"),
("How do I copy a local file to a remote server using scp?", "scp -P 2222 local_file.txt user@remote-host:/tmp/"),
("How do I view open listening network ports?", "netstat -tulpn"),
("How do I check repository status in git?", "git status"),
("How do I stage all changed files in git?", "git add ."),
("How do I commit staged changes with a message?", 'git commit -m "feat: implement terminal parser"'),
("How do I push commits to remote main branch?", "git push origin main"),
("How do I create and switch to a new git branch?", "git checkout -b feature/new-architecture"),
("How do I view compact git log history?", "git log --oneline -n 10"),
("How do I discard all unstaged local changes in git?", "git checkout -- ."),
("How do I install python packages from requirements?", "pip install -r requirements.txt"),
("How do I install npm dependencies?", "npm install"),
("How do I update package lists on Ubuntu?", "sudo apt update && sudo apt upgrade -y"),
("How do I build a Docker image with tag?", "docker build -t myapp:latest ."),
("How do I run an interactive container with volume mount?", "docker run -it -v $(pwd):/app -p 8080:8080 myapp:latest /bin/bash"),
("How do I view running docker containers?", "docker ps -a"),
("How do I compress a folder into a tar.gz archive?", "tar -czvf archive.tar.gz target_directory/"),
("How do I extract a tar.gz archive?", "tar -xzvf archive.tar.gz"),
("How do I unzip a zip file to a specific destination?", "unzip file.zip -d /path/to/destination/")
]
SHELL_INTERACTIONS = [
"$ cd ..\n$ pwd\n/home/user\n$ ls -la\ntotal 32\ndrwxr-xr-x 4 user user 4096 Aug 2 00:00 .\ndrwxr-xr-x 8 user user 4096 Aug 2 00:00 ..\n-rw-r--r-- 1 user user 220 Aug 2 00:00 .bashrc",
"$ mkdir project && cd project\n$ git init\nInitialized empty Git repository in /home/user/project/.git/\n$ touch main.py README.md\n$ git status\nOn branch main\nUntracked files:\n\tREADME.md\n\tmain.py",
'$ grep -rn "import torch" src/\nsrc/model.py:1:import torch\nsrc/train.py:2:import torch\nsrc/utils.py:1:import torch',
"$ chmod +x build.sh\n$ ./build.sh\n[INFO] Building release binary...\n[SUCCESS] Build completed in 2.4s.",
"$ curl -I https://api.github.com\nHTTP/2 200\nserver: GitHub.com\ndate: Sun, 02 Aug 2026 00:00:00 GMT\ncontent-type: application/json; charset=utf-8",
"$ ps aux | grep python\nuser 12345 98.2 4.1 452104 338102 ? Rsl 00:00 12:30 python train.py\nuser 12390 0.0 0.0 6200 892 pts/0 S+ 00:15 0:00 grep python",
"$ df -h\nFilesystem Size Used Avail Use% Mounted on\n/dev/sda1 99G 32G 63G 34% /\ntmpfs 7.8G 0 7.8G 0% /dev/shm",
'$ git commit -m "fix: resolve permission issue"\n[main a1b2c3d] fix: resolve permission issue\n 2 files changed, 14 insertions(+), 3 deletions(-)\n$ git push origin main\nTo github.com:user/repo.git\n e4f5g6h..a1b2c3d main -> main'
]
jsonl_file = r"c:\Users\asd\Documents\projs1\5m-terminal-lm\terminal_cli_commands.jsonl"
txt_file = r"c:\Users\asd\Documents\projs1\5m-terminal-lm\terminal_cli_commands.txt"
txt_gz = r"c:\Users\asd\Documents\projs1\5m-terminal-lm\terminal_cli_commands.txt.gz"
sample_file = r"c:\Users\asd\Documents\projs1\5m-terminal-lm\terminal_cli_sample.txt"
print("[Dataset] Generating 50,000 pure Linux CLI command entries...")
entries = []
txt_lines = []
for i in range(35000):
qa = random.choice(COMMAND_TEMPLATES)
entry = {
"id": i,
"type": "qa_pair",
"question": qa[0],
"command": qa[1],
"formatted_dialogue": f"User: {qa[0]}\nAssistant: Run `{qa[1]}`\n"
}
entries.append(entry)
txt_lines.append(entry["formatted_dialogue"])
for i in range(15000):
session = random.choice(SHELL_INTERACTIONS)
entry = {
"id": 35000 + i,
"type": "shell_session",
"session_log": session,
"formatted_dialogue": f"```session\n{session}\n```\n"
}
entries.append(entry)
txt_lines.append(entry["formatted_dialogue"])
random.shuffle(entries)
random.shuffle(txt_lines)
# Save JSONL
print(f"[Save] Saving {len(entries):,} JSONL entries...")
with open(jsonl_file, "w", encoding="utf-8") as f:
for item in entries:
f.write(json.dumps(item) + "\n")
# Save TXT
full_txt = "\n".join(txt_lines)
with open(txt_file, "w", encoding="utf-8") as f:
f.write(full_txt)
# Compress to GZ
print("[Compressing] Creating terminal_cli_commands.txt.gz...")
with open(txt_file, "rb") as f_in, gzip.open(txt_gz, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
# Save sample preview
with open(sample_file, "w", encoding="utf-8") as f:
f.write("\n".join(txt_lines[:500]))
jsonl_mb = os.path.getsize(jsonl_file) / (1024 * 1024)
gz_mb = os.path.getsize(txt_gz) / (1024 * 1024)
print(f"[Dataset Size] JSONL: {jsonl_mb:.2f} MB | Compressed GZ: {gz_mb:.2f} MB")
# Create Dataset README explaining origin
readme_content = f"""---
license: mit
language:
- en
tags:
- terminal
- cli
- linux
- bash
- shell
- coding
- synthetic
pretty_name: Linux Terminal & CLI Commands Corpus
size_categories:
- 10K<n<100K
---
# ๐Ÿ’ป Pure Linux Terminal & CLI Commands Dataset
This repository contains **{len(entries):,} pure Linux CLI command scenarios, shell navigation interactions, and bash command Q&A pairs**.
---
## ๐Ÿง How This Dataset Came To Exist
Small language models (such as 5.0 Million parameter models) face a severe **data scarcity and noise problem**: web text dumps (like Common Crawl) contain noisy HTML artifacts, broken code, and rambling prose that dilute small neural networks.
To train a tiny 5M parameter model to navigate Linux, run commands, and assist with terminal syntax with **100% accuracy and zero noise**, we engineered a **Synthesized Shell Compilation Engine** ([`terminal_dataset.py`](https://huggingface.co/kipasyangin5/5m-terminal-lm-chinchilla/blob/main/training_code/terminal_dataset.py)):
1. **Structured Command Pair Generation**: Programmatically synthesizes natural language user queries mapped to exact, un-corrupted Linux CLI commands (`cd ..`, `ls -la`, `mkdir -p`, `grep -rn`, `chmod +x`, `git commit`, `docker run`, `curl`, `df -h`, `free -h`).
2. **Interactive Shell Session Logs**: Generates multi-turn terminal session logs (`$ cd .. \n $ pwd \n /home/user`) to teach the model causal terminal prompt mechanics.
3. **Chained Execution Logic**: Generates multi-command shell pipelines (`$ mkdir project && cd project && git init`).
---
## ๐Ÿ“Š Dataset Schema & Files
| File | Format | Description |
| :--- | :--- | :--- |
| **`terminal_cli_commands.jsonl`** | JSON Lines | Structured JSON entries containing `question`, `command`, and `formatted_dialogue`. |
| **`terminal_cli_commands.txt.gz`** | Compressed Text | Gzip-compressed raw text stream for direct PyTorch DataLoader streaming. |
| **`terminal_cli_sample.txt`** | Plain Text | 500-line sample preview for instant browser inspection. |
### JSONL Sample Entry:
```json
{{
"id": 42,
"type": "qa_pair",
"question": "How do I navigate up one directory?",
"command": "cd ..",
"formatted_dialogue": "User: How do I navigate up one directory?\\nAssistant: Run `cd ..`\\n"
}}
```
---
## ๐Ÿ”— Related Models & Code
* **5M Chinchilla Model**: [`kipasyangin5/5m-terminal-lm-chinchilla`](https://huggingface.co/kipasyangin5/5m-terminal-lm-chinchilla)
* **5M Saturated Model**: [`kipasyangin5/5m-terminal-lm-saturated`](https://huggingface.co/kipasyangin5/5m-terminal-lm-saturated)
* **Complete Training Code**: [`kipasyangin5/5m-terminal-lm-chinchilla/tree/main/training_code`](https://huggingface.co/kipasyangin5/5m-terminal-lm-chinchilla/tree/main/training_code)
* **Live Playground Space**: [`kipasyangin5/5m-terminal-lm-chat`](https://huggingface.co/spaces/kipasyangin5/5m-terminal-lm-chat)
"""
readme_path = r"c:\Users\asd\Documents\projs1\5m-terminal-lm\cli_README.md"
with open(readme_path, "w", encoding="utf-8") as f:
f.write(readme_content)
# Upload Dataset Repo to Hugging Face
api = HfApi()
repo_id = "kipasyangin5/terminal-cli-commands-dataset"
print(f"[HuggingFace] Creating Dataset Repository: '{repo_id}'...")
api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True)
print("[HuggingFace] Uploading CLI dataset files...")
api.upload_file(
path_or_fileobj=readme_path,
path_in_repo="README.md",
repo_id=repo_id,
repo_type="dataset",
commit_message="Add CLI dataset README card"
)
api.upload_file(
path_or_fileobj=jsonl_file,
path_in_repo="terminal_cli_commands.jsonl",
repo_id=repo_id,
repo_type="dataset",
commit_message="Upload JSONL CLI commands dataset"
)
api.upload_file(
path_or_fileobj=txt_gz,
path_in_repo="terminal_cli_commands.txt.gz",
repo_id=repo_id,
repo_type="dataset",
commit_message="Upload compressed raw CLI text stream"
)
api.upload_file(
path_or_fileobj=sample_file,
path_in_repo="terminal_cli_sample.txt",
repo_id=repo_id,
repo_type="dataset",
commit_message="Add sample preview text"
)
print(f"๐Ÿš€ [SUCCESS] Pure CLI Commands Dataset is live at: https://huggingface.co/datasets/{repo_id}")