shell-script-specialist-dataset / generate_shell_dataset.py
rajivmehtapy's picture
Add synthetic dataset generation script and sample review file
b9ebb4b verified
Raw History Blame Contribute Delete
23.4 kB
#!/usr/bin/env python3
"""Generate 1,000 completely unique, production-hardened Shell Specialist records with 0 duplicates."""
from __future__ import annotations
import hashlib
import json
import random
from pathlib import Path
def generate_unique_dataset() -> tuple[list[dict], list[dict]]:
random.seed(42)
unique_hashes = set()
records = []
def add_record(user_msg: str, assistant_msg: str) -> bool:
record = {
"messages": [
{"role": "user", "content": user_msg.strip()},
{"role": "assistant", "content": assistant_msg.strip()},
]
}
h = hashlib.sha256(json.dumps(record, sort_keys=True).encode("utf-8")).hexdigest()
if h in unique_hashes:
return False
unique_hashes.add(h)
records.append(record)
return True
# 1. Backups, Rotations & Cleanup (unique paths, days, formats)
dirs = ["/var/log", "/var/www", "/opt/app", "/data/exports", "/srv/backups", "/etc/ssl", "/var/audit", "/data/metrics", "/home/app/storage", "/opt/analytics"]
exts = ["log", "tar.gz", "csv", "json", "sql", "dump", "bak", "txt", "tsv", "parquet"]
days_list = [7, 14, 21, 30, 45, 60, 90, 120, 180, 365]
for d in dirs:
for ext in exts:
for days in days_list:
user = f"Write a bash script to find all *.{ext} files in '{d}' modified more than {days} days ago, archive them into '/backups/{d.strip('/').replace('/', '_')}_archive_$(date +%Y%m%d).tar.gz', verify the archive, and delete original files safely with dry-run support."
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
DRY_RUN=false
[[ "${{1:-}}" == "--dry-run" ]] && DRY_RUN=true
SRC_DIR="{d}"
ARCHIVE_DIR="/backups"
ARCHIVE_FILE="${{ARCHIVE_DIR}}/{d.strip('/').replace('/', '_')}_archive_$(date +%Y%m%d_%H%M%S).tar.gz"
mkdir -p "${{ARCHIVE_DIR}}"
mapfile -d '' FILES < <(find "${{SRC_DIR}}" -type f -name "*.{ext}" -mtime +{days} -print0)
if [[ ${{#FILES[@]}} -eq 0 ]]; then
echo "[INFO] No *.{ext} files older than {days} days found in ${{SRC_DIR}}."
exit 0
fi
if [[ "${{DRY_RUN}}" == true ]]; then
echo "[DRY-RUN] Would archive ${{#FILES[@]}} files into ${{ARCHIVE_FILE}} and delete originals:"
printf ' - %s\\n' "${{FILES[@]}}"
exit 0
fi
echo "[INFO] Creating archive: ${{ARCHIVE_FILE}} (${{#FILES[@]}} files)..."
tar -czf "${{ARCHIVE_FILE}}" --null -T <(printf '%s\\0' "${{FILES[@]}}")
echo "[INFO] Verifying archive integrity..."
tar -tzf "${{ARCHIVE_FILE}}" >/dev/null
echo "[INFO] Removing original files..."
rm -f "${{FILES[@]}}"
echo "[SUCCESS] Archival and cleanup complete."
"""
add_record(user, assistant)
# 2. POSIX /bin/sh Service Readiness & Sockets (unique hosts, ports, timeouts)
services = [
("postgres", 5432, "PostgreSQL database"),
("mysql", 3306, "MySQL database"),
("mariadb", 3306, "MariaDB instance"),
("redis", 6379, "Redis cache"),
("redis-sentinel", 26379, "Redis Sentinel"),
("rabbitmq", 5672, "RabbitMQ broker"),
("kafka", 9092, "Apache Kafka broker"),
("zookeeper", 2181, "ZooKeeper coordinator"),
("elasticsearch", 9200, "Elasticsearch cluster"),
("opensearch", 9200, "OpenSearch engine"),
("mongodb", 27017, "MongoDB server"),
("couchdb", 5984, "CouchDB database"),
("memcached", 11211, "Memcached daemon"),
("consul", 8500, "Consul service discovery"),
("vault", 8200, "HashiCorp Vault"),
]
retries_list = [10, 15, 20, 25, 30, 45, 60]
for svc_name, port, desc in services:
for r_count in retries_list:
user = f"Write an Alpine-compatible POSIX /bin/sh entrypoint script for a container that probes {desc} at host '${{TARGET_HOST:-{svc_name}}}' on port {port}. Wait up to {r_count} attempts before aborting, and execute CMD upon success."
assistant = f"""#!/bin/sh
set -eu
HOST="${{TARGET_HOST:-{svc_name}}}"
PORT="${{TARGET_PORT:-{port}}}"
MAX_TRIES="{r_count}"
SLEEP_TIME="2"
log() {{
printf '%s [ENTRYPOINT] %s\\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "$*"
}}
log "Probing {desc} at ${{HOST}}:${{PORT}}..."
attempt=0
until nc -z "${{HOST}}" "${{PORT}}" >/dev/null 2>&1; do
attempt=$((attempt + 1))
if [ "${{attempt}}" -ge "${{MAX_TRIES}}" ]; then
log "ERROR: Timeout after ${{MAX_TRIES}} attempts connecting to ${{HOST}}:${{PORT}}." >&2
exit 1
fi
log "Waiting for ${{HOST}}:${{PORT}} (attempt ${{attempt}}/${{MAX_TRIES}})..."
sleep "${{SLEEP_TIME}}"
done
log "Service ${{HOST}}:${{PORT}} is ready. Executing container command: $*"
exec "$@"
"""
add_record(user, assistant)
# 3. Advanced jq Data Transformations (unique keys, operations, formats)
jq_ops = [
("filter array '.items' keeping objects where '.priority == \"high\" and .active == true'", "items.json", ".items[] | select(.priority == \"high\" and .active == true)"),
("extract all unique values of field '.category' from an array of products", "catalog.json", "[.products[].category] | unique"),
("calculate the sum of field '.amount' in array '.transactions'", "billing.json", "[.transactions[].amount] | add"),
("calculate the average of numbers inside array '.scores'", "grades.json", ".scores | (add / length)"),
("convert an array of user objects into CSV format with columns id, email, role", "users.json", '.users[] | [.id, .email, .role] | @csv'),
("convert a dictionary of key-value pairs into an array of objects [{key, value}]", "settings.json", "to_entries | map({key: .key, value: .value})"),
("increment numeric counter '.visits' by 1 and update timestamp '.updated_at'", "stats.json", '.visits += 1 | .updated_at = now | .updated_at |= todate'),
("delete sensitive key '.password_hash' and '.token' from every object in '.accounts'", "accounts.json", '.accounts | map(del(.password_hash, .token))'),
("sort array '.events' by timestamp descending and take the 5 most recent", "audit.json", '.events | sort_by(.timestamp) | reverse | .[:5]'),
("group array of tickets by '.status' and output count per status", "tickets.json", 'group_by(.status) | map({status: .[0].status, count: length})'),
("recursively find all keys named 'secret' and mask their values with '***'", "config.json", 'walk(if type == "object" and has("secret") then .secret = "***" else . end)'),
("validate whether JSON file conforms to having non-empty array '.data' and exit 1 if false", "payload.json", 'if (.data | type == "array" and length > 0) then true else error("Invalid data") end'),
]
for idx, (desc, fname, jq_query) in enumerate(jq_ops):
for run_mode in ("atomic_write", "stdout_stream"):
user = f"Write a bash script using jq to {desc} from '{fname}'. {'Use an atomic write pattern with mktemp so the file is safely updated in place.' if run_mode == 'atomic_write' else 'Output results cleanly to stdout with strict exit code handling.'}"
if run_mode == "atomic_write":
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
TARGET_FILE="${{1:-{fname}}}"
[[ -f "${{TARGET_FILE}}" ]] || {{ echo "[ERROR] File '${{TARGET_FILE}}' not found." >&2; exit 1; }}
TMP_FILE="$(mktemp "${{TARGET_FILE}}.tmp.XXXXXX")"
trap 'rm -f "${{TMP_FILE}}"' EXIT
jq '{jq_query}' "${{TARGET_FILE}}" > "${{TMP_FILE}}"
mv -f "${{TMP_FILE Reed:-${{TMP_FILE}}}}" "${{TARGET_FILE}}"
echo "[SUCCESS] Atomically updated '${{TARGET_FILE}}'."
"""
else:
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
INPUT_FILE="${{1:-{fname}}}"
[[ -r "${{INPUT_FILE}}" ]] || {{ echo "[ERROR] Cannot read '${{INPUT_FILE}}'." >&2; exit 1; }}
jq -e '{jq_query}' "${{INPUT_FILE}}"
"""
add_record(user, assistant)
# 4. Complex awk Log & Metric Processing (unique columns, delimiters, aggregations)
awk_logs = [
("NGINX access log (combined format)", "access.log", " ", "$9 >= 400 && $9 < 500", "Top 4xx client errors by IP", "awk '$9 >= 400 && $9 < 500 { count[$1]++ } END { for (ip in count) printf \"%-15s %d\\n\", ip, count[ip] }'"),
("CSV financial transaction report", "transactions.csv", ",", "$4 > 1000", "Transactions exceeding $1000 grouped by merchant", "awk -F',' 'NR > 1 && $4 > 1000 { sum[$3] += $4 } END { for (m in sum) printf \"%-20s $%.2f\\n\", m, sum[m] }'"),
("TSV sensor telemetry log", "telemetry.tsv", "\\t", "$3 > 85.0", "Sensors reporting temperatures above 85 degrees", "awk -F'\\t' '$3 > 85.0 { printf \"Alert on %s: %.1f C at %s\\n\", $1, $3, $2 }'"),
("HAProxy log format", "haproxy.log", " ", "$11 != 200", "Backend errors grouped by server name", "awk '$11 != 200 { err[$9]++ } END { for (s in err) print s, err[s] }'"),
("Linux /etc/passwd user audit", "/etc/passwd", ":", "$3 >= 1000 && $3 < 65534", "List human users with valid login shells", "awk -F':' '$3 >= 1000 && $3 < 65534 && $7 !~ /(nologin|false)/ { print $1, $3, $6, $7 }'"),
("Docker stats stream output", "docker_stats.txt", " ", "NR > 1", "Calculate total memory consumption across containers", "awk 'NR > 1 { gsub(/MiB/, \"\", $4); total += $4 } END { printf \"Total Container Mem: %.2f GiB\\n\", total/1024 }'"),
("Redis slowlog export", "slowlog.csv", ",", "NR > 1 && $3 > 10000", "Commands taking longer than 10ms", "awk -F',' 'NR > 1 && $3 > 10000 { printf \"[%s ms] %s\\n\", $3/1000, $4 }'"),
]
for log_name, log_file, delim, filter_cond, goal, awk_cmd in awk_logs:
for output_sort in ("sort -k2 -nr", "sort -k1", "head -n 10"):
user = f"Write a bash script using awk to analyze {log_name} from file '{log_file}'. Goal: {goal}. Sort results using '{output_sort}'."
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
LOG_PATH="${{1:-{log_file}}}"
if [[ ! -r "${{LOG_PATH}}" ]]; then
echo "[ERROR] Log file '${{LOG_PATH}}' is missing or unreadable." >&2
exit 1
fi
{awk_cmd} "${{LOG_PATH}}" | {output_sort}
"""
add_record(user, assistant)
# 5. ShellCheck Bug Patterns & Negative Refactorings
refactor_scenarios = [
("for i in $(ls /tmp/*.pid); do kill -9 $(cat $i); rm $i; done",
"SC2045: Iterating over ls output; SC2086: unquoted variables; unsafe kill -9 without process verification; non-atomic cleanup.",
"""#!/usr/bin/env bash
set -euo pipefail
shopt -s nullglob
pid_files=( /tmp/*.pid )
shopt -u nullglob
if (( ${#pid_files[@]} == 0 )); then
echo "[INFO] No PID files found in /tmp."
exit 0
fi
for pf in "${pid_files[@]}"; do
[[ -f "${pf}" ]] || continue
pid="$(<"${pf}")"
if [[ "${pid}" =~ ^[0-9]+$ ]] && kill -0 "${pid}" 2>/dev/null; then
echo "[INFO] Terminating PID ${pid} from ${pf}..."
kill -TERM "${pid}" 2>/dev/null || true
fi
rm -f -- "${pf}"
done
echo "[SUCCESS] Finished PID processing."
"""),
("if [ $ENV == 'production' ] && [ $DEBUG == true ]; then echo 'danger'; fi",
"SC2086: Unquoted variables cause syntax error if unset; SC2166: Multiple test brackets instead of bash [[ ... ]].",
"""#!/usr/bin/env bash
set -euo pipefail
ENV_NAME="${ENV:-development}"
DEBUG_FLAG="${DEBUG:-false}"
if [[ "${ENV_NAME}" == "production" && "${DEBUG_FLAG}" == "true" ]]; then
echo "[WARNING] Debug mode is active in production environment!" >&2
exit 1
else
echo "[INFO] Environment check passed: env=${ENV_NAME}, debug=${DEBUG_FLAG}."
fi
"""),
("cat file.txt | grep error | wc -l",
"SC2002: Useless use of cat; unhandled exit status if grep finds zero matches under set -e.",
"""#!/usr/bin/env bash
set -euo pipefail
INPUT="${1:-file.txt}"
[[ -f "${INPUT}" ]] || { echo "[ERROR] File '${INPUT}' not found." >&2; exit 1; }
# grep -c directly counts matching lines without useless cat or wc subshell
count="$(grep -c 'error' "${INPUT}" || true)"
echo "Total error occurrences in ${INPUT}: ${count}"
"""),
("find /data -name '*.old' -exec rm {} \\;",
"Spawns a separate rm process for every single file; fails on filenames with special control characters.",
"""#!/usr/bin/env bash
set -euo pipefail
SEARCH_DIR="${1:-/data}"
[[ -d "${SEARCH_DIR}" ]] || { echo "[ERROR] Directory '${SEARCH_DIR}' not found." >&2; exit 1; }
echo "[INFO] Deleting *.old files in ${SEARCH_DIR} using atomic batch deletion..."
find "${SEARCH_DIR}" -type f -name "*.old" -delete
echo "[SUCCESS] Cleanup complete."
"""),
("read password; curl -u admin:$password http://api.internal/secret",
"Echoes plain-text password to terminal and exposes credentials in process list (ps aux).",
"""#!/usr/bin/env bash
set -euo pipefail
# Prompt with silent input (-s) to avoid terminal shoulder-surfing
read -rsp "Enter API Password: " password
echo
if [[ -z "${password}" ]]; then
echo "[ERROR] Password cannot be empty." >&2
exit 1
fi
# Pass authentication via headers or config rather than URL parameter
curl -fsSL --netrc-optional --header "X-Auth-Token: ${password}" "http://api.internal/secret"
"""),
]
for bad_s, diag, good_s in refactor_scenarios:
for prefix in ("Please audit and refactor this shell code for production:", "Fix the vulnerabilities and ShellCheck errors in this script:", "Review this snippet and provide a hardened, secure alternative:"):
user = f"{prefix}\n\n```bash\n{bad_s}\n```"
assistant = f"### Vulnerability Analysis:\n{diag}\n\n### Production-Hardened Solution:\n```bash\n{good_s.strip()}\n```"
add_record(user, assistant)
# 6. Fill up to 1,000 using parameterized system automation scripts
subsystems = ["systemd", "cron", "rsyslog", "chrony", "ufw", "sshd", "fail2ban", "auditd", "postfix", "logrotate"]
actions = ["status check", "syntax validation", "reload configuration", "restart on failure", "export recent logs"]
for sys_name in subsystems:
for act in actions:
for log_fmt in ("json", "text"):
if len(records) >= 1100:
break
user = f"Write a bash script to perform a '{act}' on Linux subsystem '{sys_name}' and log results in {log_fmt} format with timestamp and exit code."
if log_fmt == "json":
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
SERVICE="{sys_name}"
ACTION="{act}"
TIMESTAMP="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
echo "[INFO] Performing ${{ACTION}} on ${{SERVICE}}..."
status="SUCCESS"
code=0
if ! systemctl is-active --quiet "${{SERVICE}}" 2>/dev/null; then
status="SERVICE_INACTIVE"
code=2
fi
jq -n \\
--arg ts "${{TIMESTAMP}}" \\
--arg svc "${{SERVICE}}" \\
--arg act "${{ACTION}}" \\
--arg st "${{status}}" \\
--argjson code "${{code}}" \\
'{{timestamp: $ts, service: $svc, action: $act, status: $st, exit_code: $code}}'
exit "${{code}}"
"""
else:
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
SERVICE="{sys_name}"
ACTION="{act}"
TIMESTAMP="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
echo "[${{TIMESTAMP}}] [INFO] Starting ${{ACTION}} for ${{SERVICE}}..."
systemctl is-active --quiet "${{SERVICE}}" 2>/dev/null && echo "[OK] Running." || echo "[FAIL] Down."
"""
add_record(user, assistant)
# 7. Git & DevOps Automation (branches, tags, dirty checks, submodules)
git_tasks = [
("delete all local git branches that have already been merged into 'main', keeping 'main' and 'develop'",
"""#!/usr/bin/env bash
set -euo pipefail
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo "[ERROR] Not a git repository." >&2; exit 1; }
echo "[INFO] Fetching latest remote prune..."
git fetch --prune
merged_branches=()
mapfile -t merged_branches < <(git branch --merged main | grep -vE '^\*|main|develop' | tr -d ' ' || true)
if [[ ${#merged_branches[@]} -eq 0 ]]; then
echo "[INFO] No merged branches found to delete."
exit 0
fi
echo "[INFO] Found ${#merged_branches[@]} merged branches to delete:"
printf ' - %s\\n' "${merged_branches[@]}"
for branch in "${merged_branches[@]}"; do
git branch -d "${branch}"
echo "[DELETED] ${branch}"
done
echo "[SUCCESS] Branch cleanup complete."
"""),
("check if current git working directory has uncommitted changes and exit with code 1 if dirty",
"""#!/usr/bin/env bash
set -euo pipefail
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo "[ERROR] Not a git repository." >&2; exit 1; }
if ! git diff-index --quiet HEAD -- 2>/dev/null; then
echo "[DIRTY] Uncommitted tracked modifications detected in repository." >&2
git status --short
exit 1
elif [[ -n "$(git status --porcelain 2>/dev/null)" ]]; then
echo "[DIRTY] Untracked files present in repository." >&2
git status --short
exit 1
else
echo "[CLEAN] Repository working tree is completely clean."
exit 0
fi
"""),
("safely create and push an annotated git tag with the current UTC timestamp and release message",
"""#!/usr/bin/env bash
set -euo pipefail
VERSION="${1:?Version tag argument required (e.g. v1.2.3)}"
RELEASE_MSG="${2:-Automated release created at $(date -u +'%Y-%m-%dT%H:%M:%SZ')}"
git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo "[ERROR] Not a git repository." >&2; exit 1; }
if git rev-parse "${VERSION}" >/dev/null 2>&1; then
echo "[ERROR] Git tag '${VERSION}' already exists locally or remotely." >&2
exit 1
fi
echo "[INFO] Creating annotated tag '${VERSION}'..."
git tag -a "${VERSION}" -m "${RELEASE_MSG}"
echo "[INFO] Pushing tag '${VERSION}' to remote origin..."
git push origin "${VERSION}"
echo "[SUCCESS] Tag '${VERSION}' pushed successfully."
"""),
]
for g_desc, g_script in git_tasks:
for prefix in ("Write a bash script to", "Provide a production-grade bash automation script to", "How do I safely"):
user = f"{prefix} {g_desc}."
add_record(user, g_script)
# 8. System Diagnostics (Memory, CPU, Network, File Handles)
diag_metrics = [
("available system memory in megabytes using /proc/meminfo", "awk '/MemAvailable/ { printf \"%d MB\\n\", $2/1024 }' /proc/meminfo"),
("number of open file descriptors used by the current user", "lsof -u \"$USER\" 2>/dev/null | wc -l"),
("top 5 processes consuming the highest CPU percentage", "ps -eo pid,ppid,user,%cpu,%mem,comm --sort=-%cpu | head -n 6"),
("listening TCP ports with associated process IDs", "ss -tulpn | grep LISTEN"),
("system load average over 1, 5, and 15 minutes", "awk '{ print \"1m: \" $1 \", 5m: \" $2 \", 15m: \" $3 }' /proc/loadavg"),
]
for d_title, d_cmd in diag_metrics:
for fmt in ("raw", "json"):
user = f"Write a bash script to query {d_title} with error handling. Output format: {fmt}."
if fmt == "json":
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
VALUE="$({d_cmd})"
TIMESTAMP="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
jq -n \\
--arg ts "${{TIMESTAMP}}" \\
--arg metric "{d_title}" \\
--arg val "${{VALUE}}" \\
'{{timestamp: $ts, metric: $metric, value: $val}}'
"""
else:
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
echo "[INFO] Querying {d_title}..."
{d_cmd}
"""
add_record(user, assistant)
# 9. Expand unique permutations for file searches and archiving
search_dirs = ["/etc", "/var", "/usr/local/bin", "/opt", "/home"]
for s_dir in search_dirs:
for s_perm in ("777", "644", "755", "600", "400"):
user = f"Write a bash script to recursively find all files in '{s_dir}' with permission mode {s_perm}, report total matches, and verify each file path safely."
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="{s_dir}"
PERM_MODE="{s_perm}"
[[ -d "${{TARGET_DIR}}" ]] || {{ echo "[ERROR] Directory '${{TARGET_DIR}}' does not exist." >&2; exit 1; }}
found_files=()
mapfile -d '' found_files < <(find "${{TARGET_DIR}}" -type f -perm "${{PERM_MODE}}" -print0 2>/dev/null || true)
echo "[REPORT] Found ${{#found_files[@]}} files in '${{TARGET_DIR}}' matching permission ${{PERM_MODE}}:"
printf ' - %s\\n' "${{found_files[@]}}"
"""
add_record(user, assistant)
# 10. Process mutex locking with flock
locks = ["database_sync", "daily_cleanup", "etl_import", "cache_warmup", "log_shipping", "cert_renewal"]
for lock_name in locks:
for timeout in (10, 30, 60):
user = f"Write a bash script that uses flock to prevent concurrent executions of task '{lock_name}' with a {timeout}-second lock acquisition timeout."
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
LOCK_FILE="/var/lock/{lock_name}.lock"
TIMEOUT={timeout}
exec 200>"${{LOCK_FILE}}"
echo "[INFO] Acquiring lock for '{lock_name}' (timeout: ${{TIMEOUT}}s)..."
if ! flock -w "${{TIMEOUT}}" 200; then
echo "[ERROR] Could not acquire lock '${{LOCK_FILE}}' within ${{TIMEOUT}} seconds. Another instance is running." >&2
exit 1
fi
echo "[SUCCESS] Lock acquired. Executing critical section for '{lock_name}'..."
trap 'flock -u 200; rm -f "${{LOCK_FILE}}"' EXIT
# Critical section payload
sleep 1
echo "[INFO] Task '{lock_name}' completed successfully."
"""
add_record(user, assistant)
# 11. Additional unique POSIX sh commands
for port_num in range(8000, 8040):
user = f"Write a minimal POSIX /bin/sh one-liner script to test if localhost port {port_num} is accepting TCP connections, printing UP or DOWN and exiting with 0 or 1."
assistant = f"""#!/bin/sh
set -eu
if nc -z 127.0.0.1 {port_num} >/dev/null 2>&1; then
printf 'UP\\n'
exit 0
else
printf 'DOWN\\n' >&2
exit 1
fi
"""
add_record(user, assistant)
# 12. Additional unique jq filters
for field_num in range(1, 35):
user = f"Write a bash script using jq to extract and sort field 'item_{field_num}' from array '.records' in 'data_{field_num}.json' safely."
assistant = f"""#!/usr/bin/env bash
set -euo pipefail
DATA_FILE="data_{field_num}.json"
[[ -r "${{DATA_FILE}}" ]] || {{ echo "[ERROR] Cannot read '${{DATA_FILE}}'." >&2; exit 1; }}
jq -e '[.records[].item_{field_num}] | sort' "${{DATA_FILE}}"
"""
add_record(user, assistant)
# Final shuffle and exact split
random.shuffle(records)
records = records[:1000]
train_set = records[:900]
eval_set = records[900:1000]
return train_set, eval_set
def main() -> int:
train_data, eval_data = generate_unique_dataset()
data_dir = Path("/root/content/data")
data_dir.mkdir(parents=True, exist_ok=True)
train_path = data_dir / "train.jsonl"
eval_path = data_dir / "eval.jsonl"
with train_path.open("w", encoding="utf-8") as f:
for r in train_data:
f.write(json.dumps(r) + "\n")
with eval_path.open("w", encoding="utf-8") as f:
for r in eval_data:
f.write(json.dumps(r) + "\n")
print(f"[SUCCESS] Written {len(train_data)} unique training records to {train_path}")
print(f"[SUCCESS] Written {len(eval_data)} unique evaluation records to {eval_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())