Skip to content

Inline-styled captions gain an extra space around every styled span on each conversion (grows every round-trip) #467

Open

Description

@rahul05ranjan

Describe the bug

Captions that contain inline styling pick up extra spaces around the styled spans when converted between formats, and the corruption grows with every round-trip: converting a file, reading it back and converting it again adds one more space around each <b>/<span> each time.

from pycaption import SAMIReader, SAMIWriter, WebVTTReader, WebVTTWriter

content = "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nHello <b>world</b> end\n"
for i in range(3):
    cs = WebVTTReader().read(content)
    sami = SAMIWriter().write(cs)          # dfxp -> sami shows the same
    print([l for l in sami.splitlines() if "Hello" in l])
    content = WebVTTWriter().write(SAMIReader().read(sami))
    print([l for l in content.splitlines() if "Hello" in l])

Output:

['    Hello  <b>world</b>  end']      # 2 spaces where the file had 1
['Hello  <b>world</b>  end']
['    Hello   <b>world</b>   end']     # 3 spaces
['Hello   <b>world</b>   end']
['    Hello    <b>world</b>    end']   # 4 spaces
...

DFXP output shows the same inflation, e.g. a WebVTT caption Hello <b>world</b> end written with DFXPWriter comes out as <span tts:fontWeight="bold">world</span> end, and SAMIWriter applied to a spec-conformant TTML file with <span tts:fontWeight="bold"> produces Hello <b>world</b> end.

Cause

  • pycaption/sami/writer.py:272 — _recreate_text appends a separator space after every text node:

    line += escape(node.content) + " "

    Text nodes already carry the original surrounding whitespace (e.g. 'Hello ' before the tag and ' end' after it), so a styled caption always ends up with a doubled space.

  • pycaption/dfxp/writer.py:267 (and 272/521) — closing spans are emitted as line.rstrip() + "</span> ", which also injects a space that the next text node usually duplicates.

The readers keep whatever spacing the writers produce, so each conversion adds another one.

Expected behavior

The styled word should keep its single spaces: Hello <b>world</b> end. A pattern that only adds the separator when both neighbors need it (or rstrip/rstrip-join on the accumulated line, like the BREAK branch already does) would fix both writers and make round-trips stable.

Environment

pycaption master (15abe12), Python 3.13, beautifulsoup4 4.13.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions