File size: 7,120 Bytes
7d93555
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""
Lines Dataset Visualizer - Flask app to visualize line segments on cropped P&ID images
Supports train/validation/test splits.
"""

import json
from flask import Flask, render_template, jsonify, send_from_directory
from pathlib import Path

app = Flask(__name__)

# Configuration
BASE_DIR = Path(__file__).parent.parent
SPLITS = ["train", "validation", "test"]

# Cache for metadata per split
_metadata_cache = {}


def get_split_dir(split: str) -> Path:
    """Get the directory for a split."""
    return BASE_DIR / split


def load_metadata(split: str):
    """Load all metadata from the jsonl file for a split."""
    if split in _metadata_cache:
        return _metadata_cache[split]
    
    split_dir = get_split_dir(split)
    metadata_file = split_dir / "metadata.jsonl"
    
    if not metadata_file.exists():
        print(f"Metadata file not found: {metadata_file}")
        _metadata_cache[split] = []
        return []
    
    metadata = []
    with open(metadata_file, 'r') as f:
        for line in f:
            if line.strip():
                metadata.append(json.loads(line))
    
    _metadata_cache[split] = metadata
    return metadata


def get_available_splits():
    """Get list of available splits that have data."""
    available = []
    for split in SPLITS:
        split_dir = get_split_dir(split)
        if split_dir.exists() and (split_dir / "metadata.jsonl").exists():
            available.append(split)
    return available


def get_sample_count(split: str):
    """Get total number of samples in a split."""
    return len(load_metadata(split))


def get_sample(split: str, idx: int) -> dict:
    """Get a single sample by index from a split."""
    metadata = load_metadata(split)
    if 0 <= idx < len(metadata):
        return metadata[idx]
    return None


def get_pipelines_in_sample(sample: dict) -> list:
    """Get unique pipelines in a sample."""
    pipelines = sample.get("lines", {}).get("pipelines", [])
    unique = sorted(set(p for p in pipelines if p))
    return unique


@app.route("/")
def index():
    """Serve the main page."""
    return render_template("index.html")


@app.route("/api/splits")
def get_splits():
    """Get available splits with their sample counts."""
    splits = get_available_splits()
    split_info = []
    for split in splits:
        metadata = load_metadata(split)
        total_lines = sum(len(m.get("lines", {}).get("segments", [])) for m in metadata)
        split_info.append({
            "name": split,
            "sample_count": len(metadata),
            "line_count": total_lines
        })
    return jsonify({"splits": split_info})


@app.route("/api/stats")
def get_stats():
    """Get overall dataset statistics."""
    total_samples = 0
    total_lines = 0
    solid_count = 0
    dashed_count = 0
    source_images = set()
    
    for split in get_available_splits():
        metadata = load_metadata(split)
        total_samples += len(metadata)
        
        for m in metadata:
            source_images.add(m.get("source_image_idx", 0))
            lines_data = m.get("lines", {})
            segments = lines_data.get("segments", [])
            line_types = lines_data.get("line_types", [])
            
            total_lines += len(segments)
            solid_count += sum(1 for t in line_types if t == "solid")
            dashed_count += sum(1 for t in line_types if t == "dashed")
    
    return jsonify({
        "total_samples": total_samples,
        "total_lines": total_lines,
        "source_images": len(source_images),
        "solid_lines": solid_count,
        "dashed_lines": dashed_count
    })


@app.route("/api/<split>/stats")
def get_split_stats(split):
    """Get statistics for a specific split."""
    if split not in get_available_splits():
        return jsonify({"error": "Split not found"}), 404
    
    metadata = load_metadata(split)
    total_lines = sum(len(m.get("lines", {}).get("segments", [])) for m in metadata)
    
    solid_count = 0
    dashed_count = 0
    source_images = set()
    
    for m in metadata:
        source_images.add(m.get("source_image_idx", 0))
        line_types = m.get("lines", {}).get("line_types", [])
        solid_count += sum(1 for t in line_types if t == "solid")
        dashed_count += sum(1 for t in line_types if t == "dashed")
    
    return jsonify({
        "split": split,
        "total_samples": len(metadata),
        "total_lines": total_lines,
        "source_images": len(source_images),
        "solid_lines": solid_count,
        "dashed_lines": dashed_count
    })


@app.route("/api/<split>/samples")
def get_all_samples(split):
    """Get list of all sample indices and basic info for a split."""
    if split not in get_available_splits():
        return jsonify({"error": "Split not found"}), 404
    
    metadata = load_metadata(split)
    samples = []
    for idx, m in enumerate(metadata):
        samples.append({
            "idx": idx,
            "file_name": m.get("file_name"),
            "source_image_idx": m.get("source_image_idx"),
            "width": m.get("width"),
            "height": m.get("height"),
            "line_count": len(m.get("lines", {}).get("segments", []))
        })
    return jsonify({"samples": samples, "count": len(samples)})


@app.route("/api/<split>/sample/<int:idx>")
def get_sample_data(split, idx):
    """Get detailed data for a single sample."""
    if split not in get_available_splits():
        return jsonify({"error": "Split not found"}), 404
    
    sample = get_sample(split, idx)
    if sample is None:
        return jsonify({"error": "Sample not found"}), 404
    
    lines_data = sample.get("lines", {})
    segments = lines_data.get("segments", [])
    line_types = lines_data.get("line_types", [])
    pipelines = lines_data.get("pipelines", [])
    
    # Build detailed line list
    lines = []
    for i, seg in enumerate(segments):
        lines.append({
            "idx": i,
            "segment": seg,
            "type": line_types[i] if i < len(line_types) else "solid",
            "pipeline": pipelines[i] if i < len(pipelines) else ""
        })
    
    return jsonify({
        "file_name": sample.get("file_name"),
        "source_image_idx": sample.get("source_image_idx"),
        "crop_idx": sample.get("crop_idx"),
        "width": sample.get("width"),
        "height": sample.get("height"),
        "lines": lines,
        "line_count": len(lines),
        "unique_pipelines": get_pipelines_in_sample(sample)
    })


@app.route("/images/<split>/<path:filename>")
def serve_image(split, filename):
    """Serve images from a split directory."""
    split_dir = get_split_dir(split)
    return send_from_directory(split_dir, filename)


if __name__ == "__main__":
    print("Starting Lines Dataset Visualizer...")
    print(f"Base directory: {BASE_DIR}")
    
    available_splits = get_available_splits()
    print(f"Available splits: {available_splits}")
    
    for split in available_splits:
        count = get_sample_count(split)
        print(f"  {split}: {count} samples")
    
    app.run(debug=True, port=5051)