Spaces:
Running
Running
File size: 40,765 Bytes
b6f361a 81fca62 b6f361a 81fca62 b6f361a bfb97c5 b6f361a d9ecc7c b6f361a d9ecc7c b6f361a f2b292d c4e5c07 f2b292d c4e5c07 f2b292d c4e5c07 f2b292d c4e5c07 f2b292d c4e5c07 f2b292d c4e5c07 f2b292d c4e5c07 f2b292d c4e5c07 81fca62 3672e55 cf53b59 5a2d8c8 cf53b59 5a2d8c8 cf53b59 5a2d8c8 cf53b59 5a2d8c8 cf53b59 e363538 93e4afe 007ae3b 93e4afe 007ae3b 93e4afe 0c2c651 9eb147c cf53b59 1ca1018 bbe4867 89cae6c 9a3cbf9 3672e55 d9ecc7c b863381 6f7a34c b863381 8fb4d34 bfb97c5 6f7a34c b863381 6f7a34c 81fca62 b6f361a 4b79268 bfb97c5 d61b118 | 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 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 | import io
import zipfile
from pathlib import Path
from PIL import Image
import pytest
from app.pipeline.html_gen import (
Segment,
_draft_alt_from_ocr,
_format_timestamp,
bundle_zip,
build_segments,
render_guide,
render_review,
)
from app.pipeline.types import SceneFrame
def _make_image(path: Path, color=(200, 50, 50)) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (32, 24), color).save(path, "JPEG")
def test_format_timestamp():
assert _format_timestamp(0) == "0:00"
assert _format_timestamp(65) == "1:05"
assert _format_timestamp(3725) == "1:02:05"
def test_draft_alt_text_does_not_leak_author_instructions():
# The draft state belongs in data-alt-draft="true", NOT in the alt text
# itself β screen readers would otherwise read "Review and rewrite" out
# loud to the end user.
with_text = _draft_alt_from_ocr("Hello world")
empty = _draft_alt_from_ocr("")
assert "Hello world" in with_text
for msg in (with_text, empty):
assert "Review and rewrite" not in msg
assert "Replace with" not in msg
def test_draft_alt_text_truncates_long_ocr():
long = "word " * 200
out = _draft_alt_from_ocr(long)
assert len(out) <= 160
def test_render_guide_includes_wcag_landmarks(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments([frame], ["Some narration."], ["OCR text"], inline_images=False)
html = render_guide("My Guide", segments, lang="en", inline_images=False)
assert '<html lang="en">' in html
assert 'role="banner"' in html
assert 'role="contentinfo"' in html
assert "<main" in html and 'id="main-content"' in html
assert "Skip to main content" in html
assert 'data-alt-draft="true"' in html
assert "<h1>" in html and "<h2" in html
assert "<title>My Guide</title>" in html
assert "Some narration." in html
assert 'class="doc-header"' in html
assert 'class="figure"' in html
assert "Auto-Generated Study Guide" in html
def test_render_guide_inline_images_embeds_data_uri(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments([frame], [""], [""], inline_images=True)
html = render_guide("Inline", segments, inline_images=True)
assert "data:image/jpeg;base64," in html
def test_render_guide_zip_mode_uses_static_folder_path(tmp_path):
# When not inlining, the template must emit static/<filename> for both
# frames and audio so the bundle has a single asset folder.
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments([frame], [["hello"]], [""], inline_images=False)
segments[0].audio_filename = "segment_0000.mp3"
html = render_guide("Zip", segments, inline_images=False)
assert "static/segment_0000.mp3" in html
assert "static/scene_0000.jpg" in html
assert "audio/segment_0000.mp3" not in html
assert "data:audio/mpeg;base64," not in html
def test_render_guide_single_mode_inlines_audio_data_uri(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments([frame], [["hello"]], [""], inline_images=True)
segments[0].audio_data_uri = "data:audio/mpeg;base64,AAAA"
html = render_guide("Single", segments, inline_images=True)
# Inline data URI present, no relative-folder reference leaking through.
assert "data:audio/mpeg;base64,AAAA" in html
assert "static/segment_0000.mp3" not in html
def test_bundle_zip_puts_all_assets_under_static(tmp_path):
from app.pipeline.html_gen import bundle_zip
import zipfile, io
img = tmp_path / "scene_0000.jpg"
_make_image(img)
audio = tmp_path / "segment_0000.mp3"
audio.write_bytes(b"\xff\xfb fake mp3")
data = bundle_zip("<html></html>", [img], audio_paths=[audio])
with zipfile.ZipFile(io.BytesIO(data)) as zf:
names = set(zf.namelist())
assert "static/scene_0000.jpg" in names
assert "static/segment_0000.mp3" in names
# No legacy audio/ folder.
assert not any(n.startswith("audio/") for n in names)
# HTML at the root, single asset folder.
top_level = {n.split("/", 1)[0] for n in names}
assert top_level == {"study-guide.html", "static"}
def test_metadata_round_trip_preserves_audio_filename(tmp_path):
from app.pipeline.metadata import (
SegmentMetadata,
load_metadata,
page_metadata_from_segments,
dump_metadata,
)
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments([frame], [["hello"]], [""], inline_images=False)
segments[0].audio_filename = "segment_0000.mp3"
page = page_metadata_from_segments(title="T", segments=segments)
out = tmp_path / "meta.json"
dump_metadata(out, page)
loaded = load_metadata(out)
assert isinstance(loaded.segments[0], SegmentMetadata)
assert loaded.segments[0].audio_filename == "segment_0000.mp3"
def test_metadata_to_segment_inlines_audio_from_static_folder(tmp_path):
from app.pipeline.html_gen import metadata_to_segment
from app.pipeline.metadata import SegmentMetadata
frames_dir = tmp_path / "static"
frames_dir.mkdir()
img = frames_dir / "scene_0000.jpg"
_make_image(img)
# New layout: audio sits alongside frames in the static dir.
(frames_dir / "segment_0000.mp3").write_bytes(b"\xff\xfb fake mp3")
sm = SegmentMetadata(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="scene_0000.jpg", section_title="t", alt_text="a",
audio_filename="segment_0000.mp3",
)
seg = metadata_to_segment(sm, frames_dir, inline_images=True)
assert seg.audio_data_uri is not None
assert seg.audio_data_uri.startswith("data:audio/mpeg;base64,")
assert seg.audio_filename == "segment_0000.mp3"
def test_metadata_to_segment_falls_back_to_legacy_audio_folder(tmp_path):
# Pre-existing on-disk bundles had a sibling `audio/` directory; the
# loader should still find clips there for backward compatibility.
from app.pipeline.html_gen import metadata_to_segment
from app.pipeline.metadata import SegmentMetadata
frames_dir = tmp_path / "static"
frames_dir.mkdir()
img = frames_dir / "scene_0000.jpg"
_make_image(img)
legacy = tmp_path / "audio"
legacy.mkdir()
(legacy / "segment_0000.mp3").write_bytes(b"\xff\xfb legacy mp3")
sm = SegmentMetadata(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="scene_0000.jpg", section_title="t", alt_text="a",
audio_filename="segment_0000.mp3",
)
seg = metadata_to_segment(sm, frames_dir, inline_images=True)
assert seg.audio_data_uri is not None
assert seg.audio_data_uri.startswith("data:audio/mpeg;base64,")
def test_metadata_to_segment_no_audio_when_inline_false(tmp_path):
from app.pipeline.html_gen import metadata_to_segment
from app.pipeline.metadata import SegmentMetadata
frames_dir = tmp_path / "static"
frames_dir.mkdir()
(frames_dir / "segment_0000.mp3").write_bytes(b"x")
img = frames_dir / "scene_0000.jpg"
_make_image(img)
sm = SegmentMetadata(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="scene_0000.jpg", section_title="t", alt_text="a",
audio_filename="segment_0000.mp3",
)
seg = metadata_to_segment(sm, frames_dir, inline_images=False)
# Filename preserved so the template can emit static/<fn>; no inlining.
assert seg.audio_filename == "segment_0000.mp3"
assert seg.audio_data_uri is None
def test_build_segments_assigns_default_section_titles(tmp_path):
img1 = tmp_path / "scene_0000.jpg"
img2 = tmp_path / "scene_0001.jpg"
_make_image(img1)
_make_image(img2)
frames = [SceneFrame(0, 0.0, 5.0, img1), SceneFrame(1, 5.0, 65.0, img2)]
segments = build_segments(frames, ["", ""], ["", ""], inline_images=False)
assert segments[0].section_title == "Segment 1 β 0:00"
assert segments[1].section_title == "Segment 2 β 0:05"
def test_render_review_emits_editor_chrome_and_bindings(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments(frame and [frame], ["The narration."], ["OCR content"], inline_images=True)
html = render_review("Review Me", segments, lang="en")
assert 'data-vgm-review="1"' in html
assert 'class="vgm-toolbar"' in html
assert 'data-action="save-json"' in html
assert 'data-action="load-json"' in html
assert 'data-action="download-html"' in html
assert 'data-bind="title"' in html
assert 'data-bind="section_title"' in html
assert 'data-bind="alt_text"' in html
assert 'data-bind="include"' in html
assert 'data-bind="narration"' in html
assert 'data-bind="ocr_text"' in html
assert 'data-bind-target="section_title"' in html
assert 'data-bind-target="alt_text"' in html
assert "The narration." in html
assert "OCR content" in html
assert 'data-included="true"' in html
assert "data:image/jpeg;base64," in html
def test_render_review_alt_text_is_textarea_for_multiline_descriptions(tmp_path):
"""Per accessibility-team feedback: the alt-text field needs room for
multi-paragraph descriptions, not a single-line input."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
html = render_review("Review Me", segments, lang="en")
# Old contract was an <input type="text" data-bind="alt_text">; the
# field is now a <textarea> so editors can write paragraphs.
assert '<textarea data-bind="alt_text"' in html
assert '<input type="text" data-bind="alt_text"' not in html
def test_render_review_image_appears_before_edit_panel(tmp_path):
"""Per accessibility-team feedback: the segment image moves above the
editable fields so editors see what they're describing first."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
html = render_review("Review Me", segments, lang="en")
figure_pos = html.find('<figure class="figure">')
panel_pos = html.find('<div class="vgm-edit-panel"')
assert figure_pos >= 0 and panel_pos >= 0
assert figure_pos < panel_pos, (
"Expected the segment <figure> to render before the .vgm-edit-panel"
)
def test_render_review_per_element_include_checkboxes(tmp_path):
"""Per accessibility-team feedback: 'include in published guide' is now
per-element, not just per-section. On-screen text defaults to included;
audio (when present) defaults to excluded."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)],
[""],
[""],
inline_images=True,
)
# Attach an audio data URI so the audio toggle renders.
segments[0].audio_data_uri = "data:audio/mpeg;base64,ZHVtbXk="
html = render_review("Review Me", segments, lang="en")
assert 'data-element-toggle="on_screen_text"' in html
assert 'data-element-toggle="audio"' in html
assert 'data-element="on_screen_text"' in html
assert 'data-element="audio"' in html
# On-screen text defaults included; audio defaults excluded so it
# doesn't carry over to the published guide by default (per team).
assert 'data-element="on_screen_text" data-include="true"' in html
# Attribute order within the <audio> tag may vary across line breaks
# in the template; just confirm both attributes appear on the element.
audio_chunk = html[html.find("<audio"): html.find("</audio>") + len("</audio>")]
assert 'data-element="audio"' in audio_chunk
assert 'data-include="false"' in audio_chunk
def test_render_guide_renders_description_below_figure(tmp_path):
"""Per accessibility-team feedback: a detailed visual description
renders as an open paragraph under the slide image."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=False)
segments[0].description = (
"A gallery of purple flower stem macro photographs is shown. "
"These demonstrate different perspectives and processing techniques."
)
html = render_guide("Desc", segments)
figure_pos = html.find("<figure")
desc_pos = html.find('class="section__description"')
assert figure_pos >= 0 and desc_pos >= 0
assert figure_pos < desc_pos, "<figure> must precede the .section__description"
assert "gallery of purple flower stem" in html
def test_render_guide_description_blanks_img_alt(tmp_path):
"""Per accessibility-team feedback: when a description is present, the
image's alt drops to "" (decorative) so screen readers read the
description below the figure instead of duplicating the meaning.
We deliberately do NOT also set role="presentation" β alt="" alone
is the WAI-recommended pattern, and role="presentation" on <img>
has spotty AT support; some readers ignore it, others still
announce the image. The empty alt is sufficient."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], ["Some OCR"], inline_images=False)
segments[0].description = "A clean visual description of the slide."
html = render_guide("Desc", segments)
assert 'alt=""' in html
assert 'role="presentation"' not in html
# The "alt needs review" page-level warning shouldn't fire either
# since the empty alt is intentional, not pending.
assert "Alt-text needs author review." not in html
def test_render_guide_no_aria_describedby_when_no_narration(tmp_path):
"""Dangling aria-describedby references are an ARIA validity bug
(WCAG 4.1.2). The audio's aria-describedby points at the narration
block β only emit it when the narration block is actually rendered."""
from app.pipeline.html_gen import Segment
img = tmp_path / "scene_0000.jpg"
_make_image(img)
seg = Segment(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="scene_0000.jpg",
image_data_uri=None,
narration=[], # no narration β audio describedby must be omitted
ocr_text="",
alt_draft="An image.",
section_title="X",
audio_data_uri="data:audio/mpeg;base64,ZHVtbXk=",
)
html = render_guide("T", [seg])
assert "<audio" in html
assert 'aria-describedby="narration-0"' not in html
def test_render_guide_drops_role_presentation_on_decorative_images(tmp_path):
"""For decorative imgs (alt=""), alt="" alone is the WAI-recommended
pattern. role="presentation" on <img> has inconsistent AT support
and is intentionally NOT emitted."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=False)
segments[0].description = "A description."
html = render_guide("T", segments)
assert 'role="presentation"' not in html
def test_render_guide_onscreen_text_summary_is_accessible_name(tmp_path):
"""The <details> block uses its <summary> as the accessible name;
a redundant aria-label would either override the summary
(visual/AT mismatch, WCAG 2.5.3) or duplicate it."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], ["On-screen text content."], inline_images=False)
html = render_guide("T", segments)
assert "<details class=\"onscreen-text\"" in html
assert "<summary>On-screen text from video</summary>" in html
# No aria-label on the details element itself.
assert 'class="onscreen-text"' in html
assert 'class="onscreen-text"\n aria-label' not in html
assert 'aria-label="On-screen text from' not in html
def test_render_guide_falls_back_to_alt_when_no_description(tmp_path):
"""Without a description, the image keeps its alt-text and the
review banner still triggers when the alt is OCR-derived."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)], [""], ["Some on-screen text"], inline_images=False
)
html = render_guide("Desc", segments)
assert 'alt=""' not in html # has a real alt draft
assert 'role="presentation"' not in html
assert "Alt-text needs author review." in html
def test_render_review_has_markdown_download_button(tmp_path):
"""Editor toolbar exposes a Download Markdown action alongside the
HTML download. Both produce single self-contained files honouring
the same per-element include toggles."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
html = render_review("Review Me", segments, lang="en")
assert 'data-action="download-markdown"' in html
assert '>Download Markdown<' in html
def test_render_review_emits_bulk_toggle_bar(tmp_path):
"""Per UX feedback: a 'Apply to all sections' bar exposes a bulk
checkbox per element type so the editor can hide/show alt-text,
transcript, etc. across the whole document in one click instead
of toggling N per-segment checkboxes."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
html = render_review("Review Me", segments, lang="en")
assert 'class="vgm-bulk"' in html
# One bulk toggle per element-include checkbox. The per-section
# "Include section" master switch is intentionally NOT here β a
# global include/exclude either does nothing or empties the guide,
# so it doesn't read as a meaningful bulk action.
for key in ("description", "alt_text", "on_screen_text", "transcript", "audio"):
assert f'data-bulk-toggle="{key}"' in html, f"missing bulk toggle for {key}"
assert 'data-bulk-toggle="include"' not in html
def test_render_review_transcript_uses_details_summary(tmp_path):
"""Per UX feedback: narration sections are now collapsible (rendered
as a <details> with summary 'Transcript'), default closed, and
excluded from the published output unless the editor opts in via
the per-element include checkbox (also default off)."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)], [["A paragraph."]], [""], inline_images=True
)
html = render_review("Review Me", segments, lang="en")
assert '<details class="narration"' in html
assert "<summary>Transcript</summary>" in html
# Default include = false; matches the per-element checkbox default.
assert 'data-element="transcript"' in html
assert 'data-include="false"' in html
# The old <h3>Narration</h3> heading is gone β <summary> labels the
# block for AT in its place.
assert '<h3 class="sr-only" id="narration-label-' not in html
def test_render_review_has_alt_text_and_transcript_include_checkboxes(tmp_path):
"""The fieldset must expose include checkboxes for alt-text and
transcript, both default off."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
html = render_review("Review Me", segments, lang="en")
assert 'data-element-toggle="alt_text"' in html
assert 'data-element-toggle="transcript"' in html
# Both checkboxes render UNCHECKED by default β feature should be
# opt-in per the team's feedback.
import re
for key in ("alt_text", "transcript"):
m = re.search(
r'<input[^>]*data-element-toggle="' + key + r'"[^>]*>',
html,
)
assert m, f"missing {key} include checkbox"
assert "checked" not in m.group(0), (
f"{key} include checkbox should default unchecked"
)
def test_render_review_renames_description_label_to_scene(tmp_path):
"""The user-facing label for the description field is now
'Scene description', not 'Detailed description'."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
html = render_review("Review Me", segments, lang="en")
assert "Scene description (under the image)" in html
assert "Detailed description (under the image)" not in html
def test_render_guide_wraps_narration_in_collapsed_details(tmp_path):
"""Server-side render uses the same Transcript-in-<details> shape so
editor and CLI flows stay consistent."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)],
[["The narration text."]],
[""],
inline_images=False,
)
html = render_guide("T", segments)
assert '<details class="narration"' in html
assert "<summary>Transcript</summary>" in html
# No `open` attribute β collapsed by default in every browser.
assert "<details class=\"narration\" open" not in html
# Old heading is gone.
assert '<h3 class="sr-only" id="narration-label-' not in html
def test_render_review_suppresses_alt_review_caption_when_description_present(tmp_path):
"""The figcaption "Alt-text needs author review." is misleading once
a description is carrying the meaning β alt is intentionally empty,
not pending review. Suppress it in both the editor view and the
downloadable HTML."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
# Sanity: without a description, the caption renders (review-needed signal).
html_warn = render_review("Review Me", segments, lang="en")
assert "Alt-text needs author review." in html_warn
# With a description set, the caption is gone β even though
# alt_text_reviewed is still False.
segments[0].description = "A clean visual description."
assert segments[0].alt_text_reviewed is False
html_ok = render_review("Review Me", segments, lang="en")
assert "Alt-text needs author review." not in html_ok
def test_render_review_emits_description_textarea_and_include_checkbox(tmp_path):
"""Editor must surface the new description field as an editable
paragraph below the figure plus an include checkbox in the fieldset."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments([SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=True)
html = render_review("Review Me", segments, lang="en")
assert 'data-bind="description"' in html
assert 'data-element="description"' in html
assert 'data-element-toggle="description"' in html
# Order: figure β description block β edit-panel (so the description
# sits visually under the image in the editor view).
figure_pos = html.find("<figure")
desc_pos = html.find('data-element="description"')
panel_pos = html.find('class="vgm-edit-panel"')
assert figure_pos < desc_pos < panel_pos
def test_metadata_round_trip_preserves_description(tmp_path):
"""Save β load via PageMetadata must keep description + reviewed flag."""
from app.pipeline.metadata import (
PageMetadata,
SegmentMetadata,
dump_metadata,
load_metadata,
)
page = PageMetadata(
title="t",
segments=[
SegmentMetadata(
index=0,
start_seconds=0.0,
end_seconds=5.0,
image_filename="scene_0000.jpg",
section_title="s",
alt_text="",
description="A visual description.",
description_reviewed=True,
)
],
)
path = tmp_path / "meta.json"
dump_metadata(path, page)
loaded = load_metadata(path)
assert loaded.segments[0].description == "A visual description."
assert loaded.segments[0].description_reviewed is True
def test_metadata_to_segment_sanitizes_traversal_filenames(tmp_path):
"""Security regression: a crafted audio_filename / image_filename with
'../' must not let metadata_to_segment read a file outside frames_dir
(the /edit endpoint renders untrusted JSON). Filenames are reduced to
their basename before joining to frames_dir."""
from app.pipeline.html_gen import metadata_to_segment
from app.pipeline.metadata import SegmentMetadata
# Plant a file OUTSIDE the frames dir that a traversal would reach.
secret = tmp_path / "secret.mp3"
secret.write_bytes(b"ID3secretbytes")
frames_dir = tmp_path / "static"
frames_dir.mkdir()
meta = SegmentMetadata(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="../secret.mp3", # would escape too
section_title="s", alt_text="",
image_data_uri="data:image/png;base64,AAAA", # image comes from here
audio_filename="../secret.mp3", # traversal attempt
audio_data_uri=None, # forces the disk fallback path
)
seg = metadata_to_segment(meta, frames_dir, inline_images=True)
# The secret file's bytes must NOT have been inlined as audio: basename
# sanitisation turns '../secret.mp3' into 'secret.mp3' under frames_dir,
# which doesn't exist, so no audio is produced.
assert seg.audio_data_uri is None
# And the image came from the inlined data URI, not any disk read.
assert seg.image_data_uri == "data:image/png;base64,AAAA"
def test_untimed_segments_suppress_meta_time_and_title_slide_n(tmp_path):
"""No-transcript images mode: build_segments(untimed=True) titles
sections 'Slide N' and the guide omits the meaningless time label."""
img = tmp_path / "a.png"
_make_image(img)
frames = [SceneFrame(0, 0.0, 1.0, img)]
segs = build_segments(frames, [[]], [""], inline_images=False, untimed=True)
assert segs[0].untimed is True
assert segs[0].section_title == "Slide 1"
html = render_guide("T", segs)
assert 'class="meta-time"' not in html
assert "Slide 1" in html
def test_timed_segments_still_show_meta_time(tmp_path):
"""Default (timed) path is unchanged β the time label renders."""
img = tmp_path / "a.png"
_make_image(img)
frames = [SceneFrame(0, 0.0, 65.0, img)]
segs = build_segments(frames, [[]], [""], inline_images=False)
assert segs[0].untimed is False
html = render_guide("T", segs)
assert 'class="meta-time"' in html
def test_render_from_metadata_rebuilds_editor_from_inlined_images(tmp_path):
"""The /edit flow: a self-contained export (each segment carries an
inlined image_data_uri) must rebuild the review editor WITHOUT reading
any image files off disk β frames_dir is intentionally bogus here."""
from app.pipeline.html_gen import render_from_metadata
from app.pipeline.metadata import PageMetadata, SegmentMetadata
tiny = (
"data:image/png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
)
page = PageMetadata(
title="Shared Guide",
segments=[
SegmentMetadata(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="00-00-00.png", section_title="Intro",
alt_text="", narration=["Hello."], ocr_text="",
description="A described slide.",
image_data_uri=tiny,
)
],
)
# frames_dir does not exist; must not be touched because images inline.
html = render_from_metadata(page, tmp_path / "does-not-exist", mode="review")
assert 'data-vgm-review="1"' in html # it's the editor
assert tiny in html # the inlined image is used
assert "Shared Guide" in html
assert "A described slide." in html
def test_metadata_round_trip_preserves_inlined_image_uri(tmp_path):
"""image_data_uri / audio_data_uri survive a Save -> Load cycle so the
self-contained export stays self-contained."""
from app.pipeline.metadata import (
PageMetadata,
SegmentMetadata,
dump_metadata,
load_metadata,
)
page = PageMetadata(
title="t",
segments=[
SegmentMetadata(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="00-00-00.png", section_title="s", alt_text="",
image_data_uri="data:image/png;base64,AAAA",
audio_data_uri="data:audio/mpeg;base64,BBBB",
)
],
)
path = tmp_path / "meta.json"
dump_metadata(path, page)
seg = load_metadata(path).segments[0]
assert seg.image_data_uri == "data:image/png;base64,AAAA"
assert seg.audio_data_uri == "data:audio/mpeg;base64,BBBB"
def test_metadata_round_trip_preserves_include_flags(tmp_path):
"""The per-element include flags must survive a Save β Load cycle so
the editor's toggle choices carry into the server-side ZIP re-render."""
from app.pipeline.metadata import (
PageMetadata,
SegmentMetadata,
dump_metadata,
load_metadata,
)
page = PageMetadata(
title="t",
segments=[
SegmentMetadata(
index=0,
start_seconds=0.0,
end_seconds=5.0,
image_filename="scene_0000.jpg",
section_title="s",
alt_text="Alt here.",
ocr_text="OCR here.",
narration=["Some narration."],
description="",
alt_text_included=False,
on_screen_text_included=False,
transcript_included=True,
audio_included=True,
description_included=False,
)
],
)
path = tmp_path / "meta.json"
dump_metadata(path, page)
seg = load_metadata(path).segments[0]
assert seg.alt_text_included is False
assert seg.on_screen_text_included is False
assert seg.transcript_included is True
assert seg.audio_included is True
assert seg.description_included is False
def _seg_with(tmp_path, **overrides):
"""Build a single render-ready Segment with sensible defaults for the
include-flag rendering tests."""
from app.pipeline.html_gen import Segment
img = tmp_path / "scene_0000.jpg"
_make_image(img)
base = dict(
index=0, start_seconds=0.0, end_seconds=5.0,
image_filename="scene_0000.jpg", image_data_uri=None,
narration=["The narration text."], ocr_text="On-screen text.",
alt_draft="Alt text.", section_title="Sec",
)
base.update(overrides)
return Segment(**base)
def test_render_guide_excludes_section_when_include_false(tmp_path):
"""A section the editor unchecked (include=False) must not appear in
the published guide body OR its table of contents."""
a = _seg_with(tmp_path, index=0, section_title="Kept section")
b = _seg_with(tmp_path, index=1, section_title="Dropped section", include=False)
html = render_guide("T", [a, b])
assert "Kept section" in html
assert "Dropped section" not in html
assert 'href="#section-1"' not in html
def test_render_guide_omits_transcript_when_not_included(tmp_path):
seg = _seg_with(tmp_path, transcript_included=False)
html = render_guide("T", [seg])
assert "<summary>Transcript</summary>" not in html
assert "The narration text." not in html
def test_render_guide_omits_onscreen_text_when_not_included(tmp_path):
seg = _seg_with(tmp_path, on_screen_text_included=False)
html = render_guide("T", [seg])
assert "On-screen text from video" not in html
def test_render_guide_omits_audio_when_not_included(tmp_path):
seg = _seg_with(tmp_path, audio_filename="segment_0000.mp3", audio_included=False)
html = render_guide("T", [seg], inline_images=False)
assert "<audio" not in html
def test_render_guide_blanks_alt_when_alt_not_included(tmp_path):
"""With alt-text excluded and no description, the image alt is empty."""
seg = _seg_with(tmp_path, alt_text_included=False, description="")
html = render_guide("T", [seg])
assert 'alt=""' in html
assert 'alt="Alt text."' not in html
# No "needs review" caption when alt isn't being shown at all.
assert "Alt-text needs author review." not in html
def test_render_review_audio_toggle_omitted_when_no_audio(tmp_path):
"""If the segment has neither an audio file nor an inline audio URI,
the audio include checkbox shouldn't render β there's nothing to toggle."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)],
[""],
[""],
inline_images=True,
)
html = render_review("Review Me", segments, lang="en")
assert 'data-element-toggle="audio"' not in html
assert 'data-element="audio"' not in html
def test_render_guide_emits_default_meta_and_eyebrow(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 65.0, img)], [""], [""], inline_images=False
)
html = render_guide("Meta", segments)
assert "Auto-Generated Study Guide" in html
assert "1 segment" in html
assert "Source video: 1 min 05 sec" in html
def test_render_guide_accepts_custom_eyebrow_and_meta(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=False
)
html = render_guide(
"Custom",
segments,
eyebrow="Module 4 β Energy",
meta_lines=["Lecture 3", "May 2026"],
)
assert "Module 4 β Energy" in html
assert "<span>Lecture 3</span>" in html
assert "<span>May 2026</span>" in html
def test_render_guide_renders_equations(tmp_path):
"""Math equations are the only structured-list feature that survived
the accessibility-team trim β they still render as <figure class="equation">
and pull in MathJax. Key terms / glossary / self-check were removed."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
from app.pipeline.html_gen import Segment
seg = Segment(
index=0,
start_seconds=0.0,
end_seconds=5.0,
image_filename="scene_0000.jpg",
image_data_uri=None,
narration=["A paragraph."],
ocr_text="",
alt_draft="An image.",
section_title="Energy",
math_equations=[
{"latex": "E=mc^2", "aria_label": "E equals m c squared", "label": "Eq. 1"}
],
include=True,
)
html = render_guide("Phys", [seg])
# No glossary or per-section key-terms list any more.
assert "Glossary" not in html
assert 'id="glossary-' not in html
assert 'class="narration__body"' in html
# The wrapper <figure> is structural only; MathJax's assistiveMml output
# is the proper accessible name. Wrapper aria-label / role="math" used
# to override that β we deliberately drop them.
assert "<figure class=\"equation\">" in html
assert "role=\"math\"" not in html
assert "aria-label=\"E equals m c squared\"" not in html
# The LaTeX itself still appears in the output for MathJax to typeset,
# and the label span is preserved.
assert "E=mc^2" in html
assert "Eq. 1" in html
# MathJax loader should appear automatically when equations exist.
assert "MathJax-script" in html
def test_render_guide_no_summary_or_selfcheck_blocks(tmp_path):
"""Even when seg.summary / seg.self_check_questions are populated
(e.g. loaded from an old JSON), the published guide must not render
the "In brief:" line or the self-check <details> block β both were
removed per accessibility-team feedback."""
img = tmp_path / "scene_0000.jpg"
_make_image(img)
from app.pipeline.html_gen import Segment
seg = Segment(
index=0, start_seconds=0, end_seconds=5,
image_filename="x.jpg", image_data_uri=None,
narration=["Some narration."], ocr_text="", alt_draft="An image.",
section_title="X",
summary="An advance organizer that used to render as In brief:.",
self_check_questions=["A question that used to render as a quiz?"],
)
html = render_guide("T", [seg])
assert "In brief" not in html
assert "section__summary" not in html
assert "self-check" not in html
assert "Check your understanding" not in html
assert "used to render as In brief" not in html
assert "used to render as a quiz" not in html
def test_render_guide_no_mathjax_when_no_equations(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=False
)
html = render_guide("No math", segments)
assert "MathJax-script" not in html
def test_render_guide_displays_subtitle_and_module(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
segments = build_segments(
[SceneFrame(0, 0.0, 5.0, img)], [""], [""], inline_images=False
)
html = render_guide(
"Course Title",
segments,
subtitle="A subtitle line",
module="Module 7 β Foundations",
)
assert "A subtitle line" in html
assert "Module 7 β Foundations" in html
def test_render_review_requires_inline_images(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments([frame], [""], [""], inline_images=False)
with pytest.raises(ValueError):
render_review("Bad", segments)
def test_bundle_zip_packages_html_and_images(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
segments = build_segments([frame], [""], [""], inline_images=False)
html = render_guide("Bundle", segments, inline_images=False)
data = bundle_zip(html, [img])
with zipfile.ZipFile(io.BytesIO(data)) as zf:
names = zf.namelist()
assert "study-guide.html" in names
assert "static/scene_0000.jpg" in names
# The HTML should reference the same folder name as the bundle.
assert 'src="static/scene_0000.jpg"' in html
def test_alt_warning_only_renders_when_drafts_remain(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 0.0, 5.0, img)
# All segments reviewed β no warning, no data-alt-draft attribute.
segs = build_segments([frame], [["hi"]], [""], inline_images=True)
segs[0].alt_text_reviewed = True
segs[0].alt_draft = "A diagram of the photosynthesis cycle."
html = render_guide("T", segs, inline_images=True)
assert 'class="alt-warning"' not in html
assert "data-alt-draft" not in html
assert "needs author review" not in html
# At least one segment still draft β warning present, attribute set.
segs2 = build_segments([frame], [["hi"]], [""], inline_images=True)
html2 = render_guide("T", segs2, inline_images=True)
assert 'class="alt-warning"' in html2
assert 'data-alt-draft="true"' in html2
def test_lang_attribute_falls_back_to_en_when_empty():
from app.pipeline.html_gen import render_guide
html = render_guide("T", segments=[], lang="")
assert '<html lang="en">' in html
def test_audio_aria_label_includes_section_title_and_timestamp(tmp_path):
img = tmp_path / "scene_0000.jpg"
_make_image(img)
frame = SceneFrame(0, 5.0, 12.0, img)
segs = build_segments([frame], [["hi"]], [""], inline_images=False)
segs[0].audio_filename = "segment_0000.mp3"
segs[0].section_title = "Combining AI models"
html = render_guide("T", segs, inline_images=False)
# Per-segment label, not the generic "this segment" placeholder.
assert 'aria-label="Narration audio for Combining AI models at 0:05"' in html
# And linked back to the textual narration block.
assert 'aria-describedby="narration-0"' in html
|