File size: 3,044 Bytes
8379a32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python3
import json
import logging
import sys
from pathlib import Path

# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------

ROOT = Path(__file__).parent.parent.parent
SOURCE_DIR = ROOT / "source" / "flights" / "detail"
OUTPUT_FILE = ROOT / "data" / "flights.jsonl"
PREFIX = "flight"

logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Mapper
# ---------------------------------------------------------------------------

def transform_flight(data: dict) -> dict:
    """Flatten nested flight JSON into a ChromaDB-ready format."""
    
    chroma_id = f"{PREFIX}:{int(data['id']):06d}"
    
    # Build searchable document text
    parts = []
    summary = f"Flight of the {data.get('rocket', 'rocket')}"
    if data.get('flyer'): summary += f" by {data['flyer']}"
    if data.get('motors'): summary += f" using {data['motors']} motor(s)"
    if data.get('launch_site'): summary += f" at {data['launch_site']}"
    summary += "."
    
    parts.append(summary)
    if data.get("notes"): parts.append(data["notes"])
    
    document = " ".join(parts)
    
    # Flatten metadata
    metadata = {
        "id": data["id"],
        "date": data.get("date"),
        "flyer": data.get("flyer"),
        "rocket": data.get("rocket"),
        "kit": data.get("kit"),
        "altitude_ft": data.get("altitude_ft"),
        "wind_speed_mph": data.get("conditions", {}).get("wind_speed_mph"),
        "temperature_f": data.get("conditions", {}).get("temperature_f"),
        "url": data.get("url")
    }
    
    metadata = {k: v for k, v in metadata.items() if v is not None}
    
    return {
        "id": chroma_id,
        "document": document,
        "metadata": metadata
    }

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main():
    if not SOURCE_DIR.exists():
        log.error(f"Source directory {SOURCE_DIR} not found.")
        return

    OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
    
    count = 0
    with OUTPUT_FILE.open("w", encoding="utf-8") as out:
        for shard_dir in sorted(SOURCE_DIR.iterdir()):
            if not shard_dir.is_dir(): continue
            for file_path in sorted(shard_dir.glob("*.json")):
                try:
                    with file_path.open("r", encoding="utf-8") as f:
                        raw_data = json.load(f)
                    processed = transform_flight(raw_data)
                    out.write(json.dumps(processed, ensure_ascii=False) + "\n")
                    count += 1
                except Exception as e:
                    log.error(f"Error processing {file_path}: {e}")

    log.info(f"Successfully built {count} records in {OUTPUT_FILE}")

if __name__ == "__main__":
    main()