File size: 34,041 Bytes
911e360
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
#!/usr/bin/env python3
"""Local Gurbani waveform section editor server.

Parent-folder convention:

  parent/
    Project One/
      recording.mp3
      aligned_transcript.json
    Project Two/
      another.mp3
      transcript_sections.json

Project folders are discovered recursively. A project folder must contain an
MP3 and a transcript JSON with a ``sections`` array. The JSON filename can be
``aligned_transcript.json``, ``aligned_transcript copy.json``, or
``transcript_sections.json``. When present, ``audio_file`` selects the MP3.
Hidden files and hidden directories are ignored.

Run:
  python server.py
  python server.py --parent-folder /path/to/parent --port 8000
  python server.py --parent-folder /path/to/parent --longer 20
"""
from __future__ import annotations

import argparse
import array
import json
import mimetypes
import os
import shutil
import subprocess
import sys
import tempfile
import math
from datetime import datetime
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, quote, unquote, urlparse

HOST = "127.0.0.1"
DEFAULT_PORT = 8000
AUDIO_EXTENSIONS = {".mp3", ".wav", ".m4a", ".flac", ".ogg"}
TRANSCRIPT_JSON_NAME = "aligned_transcript.json"
ROOT_PROJECT_KEY = "__root__"
BASE_DIR = Path(__file__).resolve().parent
INDEX_FILE = BASE_DIR / "index.html"


def clean_payload(payload: object) -> dict:
    """Return the input schema without adding, deleting, or normalising fields."""
    if isinstance(payload, dict):
        return payload
    elif isinstance(payload, list):
        return {"sections": payload}
    return {"sections": []}


def transcript_payload(json_path: Path) -> dict | None:
    """Read a transcript JSON candidate, rejecting unrelated JSON files."""
    try:
        payload = json.loads(json_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None
    sections = payload.get("sections") if isinstance(payload, dict) else None
    if not isinstance(sections, list):
        return None
    if not any(
        isinstance(section, dict)
        and "start_time" in section
        and "end_time" in section
        and "transcript" in section
        for section in sections
    ):
        return None
    return payload


def transcript_json_priority(path: Path) -> tuple[int, str]:
    name = path.name.casefold()
    preferred = {
        "aligned_transcript.json": 0,
        "aligned_transcript copy.json": 1,
        "transcript_sections.json": 2,
    }
    if name in preferred:
        rank = preferred[name]
    elif name.startswith("aligned_transcript"):
        rank = 3
    elif name.startswith("transcript_sections"):
        rank = 4
    else:
        rank = 5
    return rank, name


def merge_editable_fields(
    original: object,
    submitted: object,
    preserve_section_ids: list[str] | None = None,
    renumber_section_ids: bool = False,
) -> dict:
    """Apply edits while optionally retaining sections hidden by a duration filter."""
    if isinstance(original, dict):
        result = dict(original)
        original_sections = original.get("sections", [])
    else:
        result = {}
        original_sections = original if isinstance(original, list) else []

    submitted_sections = submitted.get("sections", []) if isinstance(submitted, dict) else []
    if not isinstance(original_sections, list):
        original_sections = []
    if not isinstance(submitted_sections, list):
        submitted_sections = []

    originals_by_id = {
        str(section.get("section_id")): section
        for section in original_sections
        if isinstance(section, dict) and section.get("section_id") is not None
    }
    replacements: dict[str, dict] = {}
    new_sections: list[dict] = []
    submitted_order: list[dict] = []
    editable = ("section_id", "transcript", "start_time", "end_time")
    for edited in submitted_sections:
        if not isinstance(edited, dict):
            continue
        # The editor renumbers serial IDs after a split/join. Its transient
        # source ID identifies the original section whose other fields must be
        # retained. Older clients without this marker still match by section ID.
        source_id = (
            edited.get("__source_section_id")
            if "__source_section_id" in edited
            else edited.get("section_id")
        )
        original_section = originals_by_id.get(str(source_id)) if source_id is not None else None
        if original_section is None:
            # Split/insert creates a new section. Keep only the fields required
            # by this transcript/timing schema; never copy unrelated metadata.
            new_section = {key: edited[key] for key in ("section_id", *editable) if key in edited}
            new_sections.append(new_section)
            submitted_order.append(new_section)
            continue
        new_section = dict(original_section)
        for key in editable:
            if key in edited:
                new_section[key] = edited[key]
        replacements[str(source_id)] = new_section
        submitted_order.append(new_section)

    if preserve_section_ids is None:
        # Normal mode submits every section; omission means intentional deletion.
        merged = submitted_order
    else:
        # Longer-only mode submits just the visible sections. Retain source
        # sections that were hidden by the threshold and omit deleted visible
        # sections. Then put new split sections back in audio-time order.
        preserve_ids = {str(section_id) for section_id in preserve_section_ids}
        merged = []
        for section in original_sections:
            if not isinstance(section, dict):
                continue
            source_id = section.get("section_id")
            key = str(source_id) if source_id is not None else None
            if key in replacements:
                merged.append(replacements[key])
            elif key in preserve_ids:
                merged.append(section)
        merged.extend(new_sections)
        def section_start(section: dict) -> tuple[float, float]:
            try:
                start = float(section.get("start_time", 0))
            except (TypeError, ValueError):
                start = 0.0
            try:
                end = float(section.get("end_time", start))
            except (TypeError, ValueError):
                end = start
            return start, end
        merged.sort(key=section_start)

    if renumber_section_ids:
        for index, section in enumerate(merged, 1):
            section["section_id"] = f"section-{index}"

    result["sections"] = merged
    return result


class EditorServer(ThreadingHTTPServer):
    daemon_threads = True

    def __init__(
        self, address, handler, parent_folder: Path, sections: bool,
        longer_seconds: float | None = None,
    ):
        super().__init__(address, handler)
        self.parent_folder = parent_folder.resolve()
        self.sections = sections
        self.longer_seconds = longer_seconds

    @staticmethod
    def _has_hidden_part(relative_path: Path) -> bool:
        return any(part.startswith(".") for part in relative_path.parts)

    def project_folders(self) -> list[Path]:
        """Return valid project folders found recursively below the parent."""
        projects: list[Path] = []
        try:
            candidates = list(self.parent_folder.rglob("*.json"))
            # The configured root can itself be one project.
            candidates.extend(self.parent_folder.glob("*.json"))

            for json_path in candidates:
                if not json_path.is_file() or json_path.name.startswith("."):
                    continue
                if transcript_payload(json_path) is None:
                    continue
                folder = json_path.parent.resolve()
                try:
                    relative = folder.relative_to(self.parent_folder)
                except ValueError:
                    continue
                if self._has_hidden_part(relative):
                    continue
                if self.resolve_project(self.project_key(folder)) is not None:
                    projects.append(folder)
        except OSError:
            return []

        return sorted(
            set(projects),
            key=lambda path: path.relative_to(self.parent_folder).as_posix().casefold(),
        )

    def project_key(self, folder: Path) -> str:
        relative = folder.resolve().relative_to(self.parent_folder)
        return ROOT_PROJECT_KEY if not relative.parts else relative.as_posix()

    def resolve_project(self, name: str) -> tuple[Path, Path, Path] | None:
        """Resolve a recursive project path safely below the parent folder."""
        raw_name = str(name).strip().replace("\\", "/")
        if raw_name == ROOT_PROJECT_KEY:
            folder = self.parent_folder
        else:
            relative = Path(raw_name)
            if (
                not raw_name
                or relative.is_absolute()
                or any(part in {"", ".", ".."} or part.startswith(".") for part in relative.parts)
            ):
                return None

            folder = (self.parent_folder / relative).resolve()
            try:
                checked_relative = folder.relative_to(self.parent_folder)
            except ValueError:
                return None
            if self._has_hidden_part(checked_relative):
                return None
        if not folder.is_dir():
            return None

        audio_candidates = sorted(
            (
                path for path in folder.iterdir()
                if path.is_file() and path.suffix.casefold() == ".mp3"
                and not path.name.startswith(".")
            ),
            key=lambda path: path.name.casefold(),
        )
        if not audio_candidates:
            return None

        json_options = []
        for candidate in folder.glob("*.json"):
            if candidate.name.startswith("."):
                continue
            payload = transcript_payload(candidate)
            if payload is None:
                continue
            audio_name = Path(str(payload.get("audio_file") or "")).name if isinstance(payload, dict) else ""
            matching_audio = next(
                (audio for audio in audio_candidates if audio.name.casefold() == audio_name.casefold()),
                None,
            )
            json_options.append((0 if matching_audio else 1, *transcript_json_priority(candidate), candidate, matching_audio))
        if not json_options:
            return None
        json_options.sort(key=lambda option: option[:3])
        _, _, _, json_path, audio = json_options[0]
        if audio is None:
            audio = audio_candidates[0]
        return folder, audio.resolve(), json_path.resolve()

    def resolve_audio(self, project_name: str) -> Path | None:
        project = self.resolve_project(project_name)
        return project[1] if project else None

    def resolve_json_for_audio(
        self,
        project_name: str,
        existing_only: bool = False,
    ) -> Path | None:
        project = self.resolve_project(project_name)
        return project[2] if project else None


# Auto-align tuning. These values are intentionally grouped here.
AUTO_ALIGN_FRAME_MS = 10
AUTO_ALIGN_SMOOTH_MS = 80
AUTO_ALIGN_CONTEXT_SECONDS = 1.5
AUTO_ALIGN_MIN_QUIET_SECONDS = 0.28
AUTO_ALIGN_ALLOWED_SPIKE_SECONDS = 0.03
AUTO_ALIGN_END_PADDING_SECONDS = 0.00
AUTO_ALIGN_ABSOLUTE_FLOOR = 0.00075
AUTO_ALIGN_NOISE_MULTIPLIER = 2.6
AUTO_ALIGN_CONTEXT_RATIO = 0.040
AUTO_ALIGN_MAX_THRESHOLD = 0.0060


def _percentile(values: list[float], fraction: float) -> float:
    if not values:
        return 0.0
    ordered = sorted(values)
    index = max(0, min(len(ordered) - 1, round((len(ordered) - 1) * fraction)))
    return ordered[index]


def analyse_section_tail(
    audio_path: Path,
    section_start: float,
    current_end: float,
    next_start: float | None = None,
) -> dict:
    """Extend forward to the minimum point of the first sustained low-energy valley.

    The threshold is based mainly on audio immediately before ``current_end``.
    Later bursts before the next section cannot influence that threshold. Once
    the first genuine quiet valley is confirmed, all later energy is ignored.
    The returned boundary never moves backwards and never passes ``next_start``.
    """
    sample_rate = 16000
    frame_ms = AUTO_ALIGN_FRAME_MS
    frame_seconds = frame_ms / 1000.0
    frame_samples = sample_rate * frame_ms // 1000

    scan_start = max(0.0, current_end - AUTO_ALIGN_CONTEXT_SECONDS)
    search_offset = current_end - scan_start

    if next_start is not None:
        hard_limit = max(current_end, next_start)
    else:
        hard_limit = current_end + 15.0

    scan_seconds = max(frame_seconds, min(60.0, hard_limit - scan_start))
    command = [
        "ffmpeg", "-v", "error", "-ss", f"{scan_start:.3f}",
        "-t", f"{scan_seconds:.3f}", "-i", str(audio_path),
        "-ac", "1", "-ar", str(sample_rate), "-f", "f32le", "pipe:1",
    ]
    try:
        result = subprocess.run(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=True,
        )
    except FileNotFoundError as exc:
        raise RuntimeError(
            "ffmpeg is required for Align Unvalidated but was not found"
        ) from exc
    except subprocess.CalledProcessError as exc:
        message = exc.stderr.decode("utf-8", errors="replace").strip()
        raise RuntimeError(
            f"ffmpeg could not decode the audio: {message or exc}"
        ) from exc

    samples = array.array("f")
    samples.frombytes(result.stdout)
    if not samples:
        return {"aligned_end": round(current_end, 3), "mode": "no_audio"}

    rms_values: list[float] = []
    for offset in range(0, len(samples) - frame_samples + 1, frame_samples):
        frame = samples[offset:offset + frame_samples]
        energy = sum(float(value) * float(value) for value in frame) / len(frame)
        rms_values.append(math.sqrt(energy))
    if not rms_values:
        return {"aligned_end": round(current_end, 3), "mode": "no_frames"}

    smooth_frames = max(1, round(AUTO_ALIGN_SMOOTH_MS / frame_ms))
    half_window = smooth_frames // 2
    smoothed: list[float] = []
    for i in range(len(rms_values)):
        lo = max(0, i - half_window)
        hi = min(len(rms_values), i + half_window + 1)
        smoothed.append(sum(rms_values[lo:hi]) / (hi - lo))

    search_index = max(
        0,
        min(len(smoothed) - 1, round(search_offset / frame_seconds)),
    )

    # The context ends at the existing boundary and therefore represents the
    # current section only. A later high-energy burst cannot raise or lower the
    # threshold used to identify the first valley.
    context_start = max(0, search_index - round(1.2 / frame_seconds))
    context_values = smoothed[context_start:search_index + 1]
    context_level = _percentile(context_values, 0.75)

    # Estimate the local floor from the forward search, but use only its lowest
    # portion. This adapts to recording hiss while remaining independent of a
    # later spoken or sung burst.
    forward_values = smoothed[search_index:]
    noise_floor = _percentile(forward_values, 0.10)

    threshold = max(
        AUTO_ALIGN_ABSOLUTE_FLOOR,
        noise_floor * AUTO_ALIGN_NOISE_MULTIPLIER,
        context_level * AUTO_ALIGN_CONTEXT_RATIO,
    )
    threshold = min(threshold, AUTO_ALIGN_MAX_THRESHOLD)

    quiet_frames_required = max(
        1,
        round(AUTO_ALIGN_MIN_QUIET_SECONDS / frame_seconds),
    )
    allowed_spike_frames = max(
        0,
        round(AUTO_ALIGN_ALLOWED_SPIKE_SECONDS / frame_seconds),
    )

    quiet_start: int | None = None
    quiet_count = 0
    spike_count = 0

    for i in range(search_index, len(smoothed)):
        value = smoothed[i]

        if value <= threshold:
            if quiet_start is None:
                quiet_start = i
            quiet_count += 1
            spike_count = 0
        elif quiet_start is not None and spike_count < allowed_spike_frames:
            # Permit a very short click or isolated noisy frame inside an
            # otherwise continuous valley.
            spike_count += 1
        else:
            quiet_start = None
            quiet_count = 0
            spike_count = 0

        if quiet_start is not None and quiet_count >= quiet_frames_required:
            # The valley is now confirmed. Place the boundary at the lowest
            # energy frame inside this first confirmed valley, not at the first
            # frame that crossed the threshold. This better matches the visual
            # low point in the waveform and still prevents a later burst from
            # being included.
            confirmed_end = i + 1
            valley_values = smoothed[quiet_start:confirmed_end]
            minimum_offset = min(
                range(len(valley_values)),
                key=valley_values.__getitem__,
            )
            minimum_index = quiet_start + minimum_offset
            minimum_time = scan_start + minimum_index * frame_seconds
            valley_start_time = scan_start + quiet_start * frame_seconds

            aligned_end = max(
                current_end,
                minimum_time + AUTO_ALIGN_END_PADDING_SECONDS,
            )
            if next_start is not None:
                aligned_end = min(aligned_end, next_start)
            return {
                "aligned_end": round(aligned_end, 3),
                "mode": "first_valley_minimum",
                "threshold": threshold,
                "noise_floor": noise_floor,
                "context_level": context_level,
                "valley_start": round(valley_start_time, 3),
                "valley_minimum": round(minimum_time, 3),
                "valley_minimum_energy": valley_values[minimum_offset],
            }

    if next_start is not None:
        aligned_end = next_start
        mode = "next_section_start"
    else:
        aligned_end = scan_start + len(smoothed) * frame_seconds
        mode = "scan_limit"

    return {
        "aligned_end": round(max(current_end, aligned_end), 3),
        "mode": mode,
        "threshold": threshold,
        "noise_floor": noise_floor,
        "context_level": context_level,
    }


def project_validation_summary(json_path: Path) -> dict:
    """Return validation progress without modifying the project JSON."""
    try:
        payload = json.loads(json_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return {
            "all_validated": False,
            "validated_count": 0,
            "section_count": 0,
        }

    if isinstance(payload, dict):
        sections = payload.get("sections", [])
    elif isinstance(payload, list):
        sections = payload
    else:
        sections = []

    if not isinstance(sections, list):
        sections = []

    valid_sections = [section for section in sections if isinstance(section, dict)]
    validated_count = sum(
        1 for section in valid_sections if section.get("validated") is True
    )
    section_count = len(valid_sections)

    return {
        # An empty project is not treated as completed.
        "all_validated": section_count > 0 and validated_count == section_count,
        "validated_count": validated_count,
        "section_count": section_count,
    }


def sections_over_duration(json_path: Path, seconds: float) -> list[dict]:
    """Read sections whose audio span is strictly longer than the threshold."""
    try:
        payload = json.loads(json_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return []
    sections = payload.get("sections", []) if isinstance(payload, dict) else payload
    if not isinstance(sections, list):
        return []
    result = []
    for section in sections:
        if not isinstance(section, dict):
            continue
        try:
            duration = float(section.get("end_time", 0)) - float(section.get("start_time", 0))
        except (TypeError, ValueError):
            continue
        if duration > seconds:
            result.append(section)
    return result


class Handler(BaseHTTPRequestHandler):
    server_version = "GurbaniSectionEditor/recursive-projects-v6-valley-minimum"

    @property
    def app(self) -> EditorServer:
        return self.server  # type: ignore[return-value]

    def log_message(self, fmt: str, *args):
        sys.stdout.write("[%s] %s\n" % (self.log_date_time_string(), fmt % args))

    def send_json(self, data: object, status: int = 200):
        body = json.dumps(data, ensure_ascii=False).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)

    def send_error_json(self, status: int, message: str):
        self.send_json({"error": message}, status)

    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path
        query = parse_qs(parsed.query)

        if path == "/":
            try:
                body = INDEX_FILE.read_bytes()
            except OSError as exc:
                return self.send_error_json(500, f"Cannot read index.html: {exc}")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(body)
            return

        if path == "/api/server-info":
            return self.send_json({
                "version": "mp3-aligned-transcript-v3",
                "parent_folder": str(self.app.parent_folder),
                "longer_seconds": self.app.longer_seconds,
                "project_rule": "recursive non-hidden folders containing a transcript JSON with sections and an MP3",
            })

        if path == "/api/files":
            files = []
            for folder in self.app.project_folders():
                project_key = self.app.project_key(folder)
                project = self.app.resolve_project(project_key)
                if project is None:
                    continue
                _, audio, json_path = project
                validation = project_validation_summary(json_path)
                if self.app.longer_seconds is not None:
                    matching_sections = sections_over_duration(
                        json_path, self.app.longer_seconds
                    )
                    if not matching_sections:
                        continue
                    validated_count = sum(
                        1 for section in matching_sections
                        if section.get("validated") is True
                    )
                    validation = {
                        "all_validated": validated_count == len(matching_sections),
                        "validated_count": validated_count,
                        "section_count": len(matching_sections),
                    }
                files.append({
                    "name": project_key,
                    "display_name": (
                        self.app.parent_folder.name
                        if project_key == ROOT_PROJECT_KEY
                        else project_key.replace("/", " / ")
                    ),
                    "audio_name": audio.name,
                    "audio_file_name": audio.name,
                    "json_name": json_path.name,
                    "has_json": True,
                    "all_validated": validation["all_validated"],
                    "validated_count": validation["validated_count"],
                    "section_count": validation["section_count"],
                    "audio_size": audio.stat().st_size,
                    "modified": datetime.fromtimestamp(
                        max(audio.stat().st_mtime, json_path.stat().st_mtime)
                    ).isoformat(timespec="seconds"),
                })
            return self.send_json({
                "folder": str(self.app.parent_folder),
                "longer_seconds": self.app.longer_seconds,
                "files": files,
            })

        if path == "/api/project":
            name = query.get("name", [""])[0]
            project = self.app.resolve_project(name)
            if project is None:
                return self.send_error_json(
                    404,
                    "Project folder not found or it does not contain a transcript JSON with sections and an MP3",
                )
            folder, audio, json_path = project
            try:
                payload = json.loads(json_path.read_text(encoding="utf-8"))
            except Exception as exc:
                return self.send_error_json(500, f"Cannot read JSON: {exc}")
            return self.send_json({
                "audio_name": name,
                "audio_file_name": audio.name,
                "project_name": name,
                "json_name": json_path.name,
                "audio_url": f"/api/audio?name={quote(name)}",
                "data": clean_payload(payload),
            })

        if path == "/api/audio":
            name = query.get("name", [""])[0]
            audio = self.app.resolve_audio(name)
            if not audio:
                return self.send_error_json(404, "Project audio not found")
            return self.serve_file_with_range(audio)

        self.send_error_json(404, "Not found")

    def serve_file_with_range(self, path: Path):
        size = path.stat().st_size
        mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
        start, end = 0, size - 1
        status = HTTPStatus.OK
        range_header = self.headers.get("Range")
        if range_header and range_header.startswith("bytes="):
            try:
                spec = range_header.removeprefix("bytes=").split(",", 1)[0]
                first, last = spec.split("-", 1)
                if first:
                    start = int(first)
                if last:
                    end = int(last)
                else:
                    end = size - 1
                start = max(0, min(start, size - 1))
                end = max(start, min(end, size - 1))
                status = HTTPStatus.PARTIAL_CONTENT
            except Exception:
                return self.send_error_json(416, "Invalid Range header")
        length = end - start + 1
        self.send_response(status)
        self.send_header("Content-Type", mime)
        self.send_header("Accept-Ranges", "bytes")
        self.send_header("Content-Length", str(length))
        if status == HTTPStatus.PARTIAL_CONTENT:
            self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
        self.send_header("Cache-Control", "no-cache")
        self.end_headers()
        with path.open("rb") as handle:
            handle.seek(start)
            remaining = length
            while remaining > 0:
                chunk = handle.read(min(1024 * 1024, remaining))
                if not chunk:
                    break
                self.wfile.write(chunk)
                remaining -= len(chunk)

    def do_POST(self):
        parsed = urlparse(self.path)
        if parsed.path not in {"/api/save", "/api/auto-align"}:
            return self.send_error_json(404, "Not found")
        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            return self.send_error_json(400, "Invalid Content-Length")
        if length <= 0 or length > 50 * 1024 * 1024:
            return self.send_error_json(400, "Invalid request size")
        try:
            request = json.loads(self.rfile.read(length).decode("utf-8"))
        except Exception as exc:
            return self.send_error_json(400, f"Invalid JSON request: {exc}")
        if not isinstance(request, dict):
            return self.send_error_json(400, "Request must be an object")

        if parsed.path == "/api/auto-align":
            audio_name = str(request.get("audio_name") or "")
            audio = self.app.resolve_audio(audio_name)
            if not audio:
                return self.send_error_json(404, "Project audio not found")
            try:
                section_start = float(request.get("section_start", 0))
                current_end = float(request.get("current_end", section_start))
                next_value = request.get("next_start")
                next_start = None if next_value is None else float(next_value)
            except (TypeError, ValueError):
                return self.send_error_json(400, "Invalid section timing")
            if current_end <= section_start:
                return self.send_error_json(400, "Section end must be after its start")
            if next_start is not None and next_start <= section_start + 0.02:
                return self.send_error_json(400, "Next section must start after this section")
            try:
                result = analyse_section_tail(
                    audio, section_start, current_end, next_start
                )
            except RuntimeError as exc:
                return self.send_error_json(500, str(exc))
            if result.get("mode") == "next_section_start":
                result["message"] = "Audible energy reaches the next section"
            elif result["aligned_end"] != round(current_end, 3):
                result["message"] = "Aligned to the end of the audible waveform"
            else:
                result["message"] = "No reliable waveform end was found"
            return self.send_json(result)

        audio_name = str(request.get("audio_name") or "")
        json_path = self.app.resolve_json_for_audio(audio_name)
        if not json_path:
            return self.send_error_json(400, "Invalid audio name")
        try:
            original_payload = json.loads(json_path.read_text(encoding="utf-8"))
        except Exception as exc:
            return self.send_error_json(500, f"Cannot read source JSON: {exc}")
        preserve_ids_value = request.get("preserve_section_ids")
        preserve_ids = (
            [str(value) for value in preserve_ids_value]
            if isinstance(preserve_ids_value, list)
            else None
        )
        payload = merge_editable_fields(
            original_payload,
            request.get("data"),
            preserve_section_ids=preserve_ids,
            renumber_section_ids=request.get("renumber_section_ids") is True,
        )

        try:
            json_path.parent.mkdir(parents=True, exist_ok=True)
            backup = None
            if json_path.exists():
                backup = json_path.with_suffix(json_path.suffix + ".bak")
                shutil.copy2(json_path, backup)
            fd, temp_name = tempfile.mkstemp(prefix=json_path.name + ".", suffix=".tmp", dir=json_path.parent)
            try:
                with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
                    json.dump(payload, handle, ensure_ascii=False, indent=2)
                    handle.write("\n")
                    handle.flush()
                    os.fsync(handle.fileno())
                os.replace(temp_name, json_path)
            finally:
                if os.path.exists(temp_name):
                    os.unlink(temp_name)
        except Exception as exc:
            return self.send_error_json(500, f"Save failed: {exc}")

        return self.send_json({
            "saved": True,
            "json_name": json_path.name,
            "sections": len(payload["sections"]),
            "backup_name": backup.name if backup else None,
            "data": payload,
        })


def main() -> int:
    parser = argparse.ArgumentParser(
        description=(
            "Serve the editor from a parent folder and recursively discover "
            "folders containing transcript JSON files with sections and an MP3"
        )
    )
    parser.add_argument(
        "--parent-folder",
        "--kirtan-folder",
        dest="parent_folder",
        default="kirtan",
        help=(
            "Parent folder searched recursively. Each project folder must contain "
            "a transcript JSON file with sections and an MP3. "
            "--kirtan-folder remains as a backwards-compatible alias."
        ),
    )
    parser.add_argument("--host", default=HOST)
    parser.add_argument("--port", type=int, default=DEFAULT_PORT)
    parser.add_argument("--sections", default=False)
    parser.add_argument(
        "--longer",
        type=float,
        default=None,
        metavar="SECONDS",
        help="Show only projects and sections with a duration longer than SECONDS",
    )
    args = parser.parse_args()

    if args.longer is not None and args.longer <= 0:
        parser.error("--longer must be greater than 0 seconds")

    folder = Path(args.parent_folder).expanduser().resolve()
    folder.mkdir(parents=True, exist_ok=True)
    server = EditorServer(
        (args.host, args.port), Handler, folder, args.sections,
        longer_seconds=args.longer,
    )
    print("Server version: mp3-aligned-transcript-v3")
    print(f"Parent folder: {folder}")
    print("Projects: recursive non-hidden folders containing a transcript JSON with sections and an MP3")
    if args.longer is not None:
        print(f"Longer-only filter: sections longer than {args.longer:g} seconds")
    print(f"Open: http://{args.host}:{args.port}")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nStopping server")
    finally:
        server.server_close()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())