Created
April 21, 2024 10:30
-
-
Save rohan-paul/73ccbdbb7ddd6a089d0d0abc0374a629 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import textwrap | |
import torch # You missed importing the torch module. | |
device = 'cuda' if torch.cuda.is_available() else 'cpu' | |
import textwrap | |
def text_wrapper(text, width=90): | |
# Wraps the input text to the specified width | |
# Check for null, empty, or non-string input | |
if not text or not isinstance(text, str): | |
return text | |
# Validate and handle invalid width | |
if not isinstance(width, int) or width <= 0: | |
raise ValueError("Width must be a positive integer.") | |
wrapped_lines = [] | |
# splits the input text into a list of lines based on newline chars | |
# To ensures that existing paragraph or line breaks in | |
# the input text are preserved. | |
for line in text.split('\n'): | |
# Preserve indentation: i.e. detects and preserves any | |
# leading whitespace (indentation) in each line, | |
# applying it to wrapped lines as well. | |
leading_spaces = len(line) - len(line.lstrip(' ')) | |
indentation = ' ' * leading_spaces | |
# Wrap each line and add indentation to each subsequent line | |
wrapped_line = textwrap.fill(line, width=width, | |
subsequent_indent=indentation) | |
# textwrap.fill() wraps each line to the specified width. | |
# If a line is longer than width, it's broken into shorter lines, | |
# ensuring that no line exceeds the specified width. | |
# Words are not broken across lines; instead, | |
# the breaking occurs at whitespace. | |
wrapped_lines.append(wrapped_line) | |
# Finally, rejoin the individually wrapped lines into a single string, | |
# separating them with newline characters. | |
# This maintains the paragraph structure of the original text. | |
return '\n'.join(wrapped_lines) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment