Spaces:
Runtime error
Runtime error
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395import gradio as grimport reimport textwrap
def format_lyrics(text): if not text.strip(): return "" text = pre_clean_direct_fixes(text) text = remove_section_headers(text) text = expand_repetitions(text) text = clean_symbols(text) text = remove_end_punctuation(text) text = handle_contractions(text) text = normalize_spacing(text) text = format_line_breaks(text) text = fix_capitalization(text) text = handle_section_spacing(text) text = post_clean_direct_fixes(text) return text.strip()
def pre_clean_direct_fixes(text): replacements = { '\u2019': "'", '\u2018': "'", '\u201c': '"', '\u201d': '"', '\u00b4': "'", '\u201b': "'" } for curly, straight in replacements.items(): text = text.replace(curly, straight)
text = re.sub(r'[\u200B-\u200D\uFEFF]', '', text) text = re.sub(r"\bthere's is\b", r"there is", text, flags=re.IGNORECASE) text = re.sub(r"\bAnd there's is\b", r"And there is", text, flags=re.IGNORECASE) return text
def remove_section_headers(text): section_pattern = r"^[\s]*[\[(]?(verse|chorus|hook|bridge|intro|outro|pre-chorus|interlude|breakdown|skit|feat|feature)[\s]*(one|two|three|four|five|six|seven|eight|nine|ten|1st|2nd|3rd|\d+|first|second|third|fourth|fifth)?[\s]*[\])]?[\s]*:?[\s]*$" text = re.sub(section_pattern, "<SECTION_BREAK>", text, flags=re.IGNORECASE | re.MULTILINE) standalone_numbers = r"^[\s]*(one|two|three|four|five|six|seven|eight|nine|ten|1st|2nd|3rd|\d+|first|second|third|fourth|fifth)[\s]*$" text = re.sub(standalone_numbers, "<SECTION_BREAK>", text, flags=re.IGNORECASE | re.MULTILINE) v_headers = r"^[\s]*[Vv][\s]*(one|two|three|four|five|\d+)[\s]*$" text = re.sub(v_headers, "<SECTION_BREAK>", text, flags=re.IGNORECASE | re.MULTILINE) inline_pattern = r"[\[(]?(verse|chorus|hook|bridge|intro|outro|pre-chorus|interlude|breakdown|skit|feat|feature)[\s\d]*[\])]?[\s]*:?" text = re.sub(inline_pattern, "", text, flags=re.IGNORECASE) return text
def expand_repetitions(text): def expand_repeat(match): line = match.group(1).strip() count_str = match.group(2) count = int(re.search(r'\d+', count_str).group()) return (line + ", ") * (count - 1) + line pattern = r'^(.+?)\s*\([x]?(\d+)[x]?\)\s*$' text = re.sub(pattern, expand_repeat, text, flags=re.MULTILINE) return text
def clean_symbols(text): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" u"\U0001F300-\U0001F5FF" u"\U0001F680-\U0001F6FF" u"\U0001F1E0-\U0001F1FF" "]+", flags=re.UNICODE) text = emoji_pattern.sub('', text) text = re.sub(r"[!?.,]{2,}", "", text) return text
def remove_end_punctuation(text): # Remove ALL punctuation at the end of lines - this is critical for platform acceptance text = re.sub(r"[.!?,;:\-\"'()]+\s*$", "", text, flags=re.MULTILINE) return text
def handle_contractions(text): contractions = { r'\bdont\b': "don't", r'\bcant\b': "can't", r'\bwont\b': "won't", r'\baint\b': "ain't", r'\bim\b': "I'm", r'\bill\b': "I'll", r'\byoure\b': "you're", r'\btheyre\b': "they're", r'\bwere\b': "we're", r'\bits\b': "it's", r'\bthats\b': "that's", r'\bwhats\b': "what's", r'\bwhos\b': "who's", r'\bwheres\b': "where's", r'\bhows\b': "how's", r'\bwhens\b': "when's" } for pattern, replacement in contractions.items(): text = re.sub(pattern, replacement, text, flags=re.IGNORECASE) # Handle acronym formatting - standardize to proper English grammar # Pattern 1: Letters with periods (R.I.P., F.B.I., etc.) -> RIP, FBI text = re.sub(r'\b([A-Za-z]\.){2,}[A-Za-z]?\.?\b', lambda m: re.sub(r'\.', '', m.group(0)).upper(), text) # Pattern 2: Short all-caps words (likely acronyms) - keep as is but ensure caps text = re.sub(r'\b[A-Z]{2,5}\b', lambda m: m.group(0).upper(), text) # Pattern 3: Mixed case short words that might be acronyms (rip -> RIP) common_acronyms = ['rip', 'dj', 'mc', 'ceo', 'fbi', 'cia', 'nasa', 'nba', 'nfl', 'mlb', 'nhl', 'ufc', 'usa', 'uk', 'nyc', 'la', 'dc'] for acronym in common_acronyms: text = re.sub(r'\b' + acronym + r'\b', acronym.upper(), text, flags=re.IGNORECASE) excluded_words = ['violin', 'ruin', 'main', 'rain', 'pain', 'gain', 'brain', 'train', 'chain', 'plain', 'strain', 'ain', 'aint'] def convert_to_full_form(match): full_word = match.group(0) word_part = "" for char in full_word: if char.isalpha(): word_part += char else: break if (word_part.lower().endswith('in') and word_part.lower() not in excluded_words and len(word_part) > 2): return word_part[:-2] + 'ing' return full_word text = re.sub(r'\b\w+in\w*\b', convert_to_full_form, text) return text
def normalize_spacing(text): text = re.sub(r' +', ' ', text) lines = [line.strip() for line in text.split('\n')] return '\n'.join(lines)
def fix_capitalization(text): lines = text.split('\n') formatted_lines = [] proper_nouns = { 'eminem': 'Eminem', 'nba': 'NBA', 'youngboy': 'Youngboy', 'cern': 'CERN', 'gpt': 'GPT', 'ai': 'AI', 'usa': 'USA', 'uk': 'UK', 'nyc': 'NYC', 'la': 'LA', 'dc': 'DC', 'dj': 'DJ', 'mc': 'MC', 'ceo': 'CEO', 'fbi': 'FBI', 'cia': 'CIA', 'nasa': 'NASA', 'nike': 'Nike', 'google': 'Google', 'apple': 'Apple', 'microsoft': 'Microsoft', 'youtube': 'YouTube', 'instagram': 'Instagram', 'facebook': 'Facebook', 'twitter': 'Twitter', 'spotify': 'Spotify', 'dm': 'DM', 'dms': 'DMs', 'pm': 'PM', 'pms': 'PMs', 'lol': 'LOL', 'omg': 'OMG', 'wtf': 'WTF', 'btw': 'BTW', 'fyi': 'FYI', 'miley cyrus': 'Miley Cyrus', 'kylo ren': 'Kylo Ren', 'miley': 'Miley', 'cyrus': 'Cyrus', 'kylo': 'Kylo', 'ren': 'Ren' } for line in lines: if line.strip() == "<SECTION_BREAK>" or not line.strip(): formatted_lines.append(line) continue line = line.lower() line = re.sub(r'\bi\b', 'I', line) line = re.sub(r'\boh my god\b', 'oh my god', line, flags=re.IGNORECASE) line = re.sub(r'(?<!oh my )\bgod\b', 'God', line) for lower_word, proper_word in proper_nouns.items(): pattern = r'\b' + re.escape(lower_word) + r'\b' line = re.sub(pattern, proper_word, line, flags=re.IGNORECASE) if line and line.strip(): line = line.strip() if line: line = line[0].upper() + line[1:] if len(line) > 1 else line.upper() formatted_lines.append(line) return '\n'.join(formatted_lines)
def format_line_breaks(text): lines = text.split('\n') formatted_lines = [] for line in lines: if line.strip() == "<SECTION_BREAK>" or not line.strip(): formatted_lines.append(line) continue if len(line) <= 55: formatted_lines.append(line) continue broken_lines = smart_line_break(line) formatted_lines.extend(broken_lines) return '\n'.join(formatted_lines)
def smart_line_break(line): if len(line) <= 40: # Even lower threshold for better rhyme structure return [line] # Connector words and common phrase starters break_words = ['and', 'but', 'so', 'cuz', 'cause', 'because', 'while', 'when', 'if', 'though', 'although', 'or', 'nor', 'yet', 'for', 'then', 'now', 'like', 'with'] words = line.split() broken_lines = [] current_line = [] for i, word in enumerate(words): current_line.append(word) current_length = len(' '.join(current_line)) # Hard limit - must break if over 50 characters (much more aggressive) if current_length > 50: if len(current_line) > 1: current_line.pop() broken_lines.append(' '.join(current_line)) current_line = [word] else: broken_lines.append(' '.join(current_line)) current_line = [] # Very aggressive rhyme detection starting at just 25+ chars elif current_length > 25: # Break after any connector words if word.lower() in break_words: broken_lines.append(' '.join(current_line)) current_line = [] # Break after commas, periods, or any punctuation elif word.endswith((',', '.', '!', '?', ';', ':')): broken_lines.append(' '.join(current_line)) current_line = [] # Aggressive break before new phrases starting at 30+ chars elif current_length > 30 and i < len(words) - 1: next_word = words[i + 1] if i + 1 < len(words) else "" # Break before any potential rhyme setup words if (next_word and (next_word[0].isupper() or next_word.lower() in ['i', 'you', 'we', 'they', 'he', 'she', 'it', 'that', 'this', 'my', 'your', 'the', 'like', 'with', 'from', 'to', 'at', 'in', 'on', 'of', 'all', 'no', 'some', 'every', 'who', 'what', 'where', 'how', 'why', 'gonna', 'gotta', 'wanna'])): broken_lines.append(' '.join(current_line)) current_line = [] # At 35+ chars, break after almost any word that could be a rhyme word elif current_length > 35: # Look for potential rhyme words (most nouns, adjectives, verbs) clean_word = word.strip('.,!?;:"()[]').lower() if (len(clean_word) > 2 and not clean_word in ['the', 'and', 'but', 'for', 'with', 'from', 'this', 'that', 'they', 'them', 'have', 'been', 'will', 'can', 'could', 'would', 'should']): broken_lines.append(' '.join(current_line)) current_line = [] if current_line: broken_lines.append(' '.join(current_line)) return broken_lines
def handle_section_spacing(text): lines = text.split('\n') final_lines = [] for i, line in enumerate(lines): if line.strip() == "<SECTION_BREAK>": if final_lines and final_lines[-1].strip() != "": final_lines.append("") else: final_lines.append(line) final_lines = [line for line in final_lines if line.strip() != "<SECTION_BREAK>"] cleaned_lines = [] prev_blank = False for line in final_lines: is_blank = line.strip() == "" if is_blank and prev_blank: continue cleaned_lines.append(line) prev_blank = is_blank return '\n'.join(cleaned_lines)
def post_clean_direct_fixes(text): lines = text.split('\n') final_lines = [] for line in lines: if line.strip(): line = line.strip() # Remove ANY punctuation from the end of lines (critical for platform acceptance) line = re.sub(r"[.!?,;:\-\"'()]+$", "", line) # Fix capitalization - EVERY line must start with a capital letter if line.lower().startswith("'til"): line = "'Til" + line[4:] elif line.startswith("'") and len(line) > 1: line = "'" + line[1].upper() + line[2:] if len(line) > 2 else "'" + line[1].upper() elif line: line = line[0].upper() + line[1:] if len(line) > 1 else line.upper() # Final check - remove any trailing punctuation that might have been missed line = re.sub(r"[.!?,;:\-\"'()]+$", "", line) final_lines.append(line) return '\n'.join(final_lines)
def download_txt(lyrics): if not lyrics.strip(): return "Please enter some lyrics to format.", None try: formatted = format_lyrics(lyrics) filename = "Formatted_Lyrics.txt" with open(filename, "w", encoding="utf-8") as f: f.write(formatted) return formatted, filename except Exception as e: return f"Error formatting lyrics: {str(e)}", None
iface = gr.Interface( fn=download_txt, inputs=gr.Textbox( lines=20, placeholder="Paste your raw lyrics here...", label="Raw Lyrics" ), outputs=[ gr.Textbox(lines=20, label="Formatted Lyrics"), gr.File(label="Download Formatted Lyrics") ], title="🎤 Enhanced Lyric Formatter by Erinem for Wendy Day", description="""Auto-formats your lyrics for streaming platforms with proper line breaks, spacing, and formatting rules. **Key Features:**• Removes section headers (Verse, Chorus, etc.)• Expands repetition notation (x2, 4x) into full text• Fixes capitalization and proper nouns• Removes end-of-line punctuation• Handles contractions and drop-G gerunds• Creates proper line breaks respecting rhyme schemes• Normalizes spacing between sections• Enhanced apostrophe handling for better compatibility """, allow_flagging="never", theme=gr.themes.Soft())
if __name__ == "__main__": iface.launch()app.pyDeleted-395