James Edmunds Claude Opus 4.6 commited on
Commit ·
d305e69
1
Parent(s): 5ccf3cf
Simplify app startup to fix blank page issue
Browse filesReplace st.status with st.info/st.spinner for reliability.
Add st.rerun() after initialization so chat input renders
cleanly on second pass.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
app.py
CHANGED
|
@@ -1,66 +1,18 @@
|
|
| 1 |
"""Main Streamlit application for lyric generation."""
|
| 2 |
import os
|
| 3 |
import streamlit as st
|
| 4 |
-
from src.generator.generator import LyricGenerator
|
| 5 |
-
from config.settings import Settings
|
| 6 |
from pathlib import Path
|
| 7 |
from datetime import datetime
|
| 8 |
|
| 9 |
-
# Set
|
| 10 |
-
os.
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
if not Settings.is_huggingface():
|
| 14 |
os.environ['DYLD_LIBRARY_PATH'] = '/usr/local/opt/sqlite/lib'
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
print("\n=== Initializing Generator ===")
|
| 20 |
-
|
| 21 |
-
if Settings.is_huggingface():
|
| 22 |
-
print("Running in HuggingFace environment")
|
| 23 |
-
print("Checking environment requirements...")
|
| 24 |
-
|
| 25 |
-
# Debug: List contents of /data directory
|
| 26 |
-
data_dir = Path("/data")
|
| 27 |
-
if data_dir.exists():
|
| 28 |
-
print("\nContents of /data directory:")
|
| 29 |
-
for item in data_dir.rglob("*"):
|
| 30 |
-
if item.is_file():
|
| 31 |
-
print(f"- {item.relative_to(data_dir)} "
|
| 32 |
-
f"({item.stat().st_size / 1024:.1f} KB)")
|
| 33 |
-
|
| 34 |
-
if not Settings.HF_TOKEN:
|
| 35 |
-
error_msg = "HuggingFace token not found."
|
| 36 |
-
print(f"Error: {error_msg}")
|
| 37 |
-
st.error(error_msg)
|
| 38 |
-
return None
|
| 39 |
-
|
| 40 |
-
# Ensure persistent storage directory exists
|
| 41 |
-
storage_path = Path("/data/processed/embeddings")
|
| 42 |
-
print(f"\nSetting up storage at: {storage_path}")
|
| 43 |
-
storage_path.mkdir(parents=True, exist_ok=True)
|
| 44 |
-
|
| 45 |
-
if storage_path.exists():
|
| 46 |
-
print("Storage directory contents:")
|
| 47 |
-
for item in storage_path.rglob("*"):
|
| 48 |
-
if item.is_file():
|
| 49 |
-
print(f"- {item.relative_to(storage_path)} "
|
| 50 |
-
f"({item.stat().st_size / 1024:.1f} KB)")
|
| 51 |
-
|
| 52 |
-
# Initialize generator
|
| 53 |
-
print("\nInitializing LyricGenerator...")
|
| 54 |
-
generator = LyricGenerator()
|
| 55 |
-
st.success("Generator initialized successfully!")
|
| 56 |
-
return generator
|
| 57 |
-
|
| 58 |
-
except Exception as e:
|
| 59 |
-
error_msg = f"Initialization failed: {str(e)}"
|
| 60 |
-
print(f"\nError: {error_msg}")
|
| 61 |
-
print(f"Error type: {type(e).__name__}")
|
| 62 |
-
st.error(error_msg)
|
| 63 |
-
return None
|
| 64 |
|
| 65 |
def main():
|
| 66 |
"""Main application function"""
|
|
@@ -69,51 +21,36 @@ def main():
|
|
| 69 |
page_icon="🎵",
|
| 70 |
layout="wide"
|
| 71 |
)
|
| 72 |
-
|
| 73 |
st.title("SongLift LyrGen2")
|
| 74 |
-
|
| 75 |
# Only run startup once per session
|
| 76 |
if 'initialized' not in st.session_state:
|
| 77 |
print("===== Application Startup at", datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "=====\n")
|
| 78 |
|
| 79 |
# Initialize generator
|
| 80 |
try:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
except Exception as e:
|
| 91 |
st.error(f"Error initializing generator: {str(e)}")
|
| 92 |
print(f"Error: {str(e)}")
|
| 93 |
import traceback
|
| 94 |
traceback.print_exc()
|
| 95 |
st.stop()
|
| 96 |
-
|
| 97 |
-
# Check OpenAI API key
|
| 98 |
-
if Settings.
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
st.error(
|
| 103 |
-
"OpenAI API key not found in HuggingFace secrets. "
|
| 104 |
-
"Please ensure OPENAI_API_KEY is set in Space settings under Secrets."
|
| 105 |
-
)
|
| 106 |
-
print("OpenAI API key not found in HF secrets")
|
| 107 |
-
st.stop()
|
| 108 |
-
else:
|
| 109 |
-
print("OpenAI API key found in HF secrets")
|
| 110 |
-
else:
|
| 111 |
-
if not Settings.OPENAI_API_KEY:
|
| 112 |
-
st.error("OpenAI API key not found in local environment")
|
| 113 |
-
st.stop()
|
| 114 |
-
|
| 115 |
-
print(f"Current deployment mode: {Settings.DEPLOYMENT_MODE}")
|
| 116 |
-
|
| 117 |
# Display chat history
|
| 118 |
for message in st.session_state.chat_history:
|
| 119 |
user_msg, assistant_msg = message
|
|
@@ -121,28 +58,27 @@ def main():
|
|
| 121 |
st.write(user_msg)
|
| 122 |
with st.chat_message("assistant"):
|
| 123 |
st.markdown(f"```\n{assistant_msg}\n```")
|
| 124 |
-
|
| 125 |
# Chat interface
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
if user_input:
|
| 130 |
with st.chat_message("user"):
|
| 131 |
st.write(user_input)
|
| 132 |
-
|
| 133 |
with st.chat_message("assistant"):
|
| 134 |
try:
|
| 135 |
-
with st.
|
| 136 |
response = st.session_state.generator.generate_lyrics(
|
| 137 |
user_input,
|
| 138 |
st.session_state.chat_history
|
| 139 |
)
|
| 140 |
-
|
| 141 |
# Store the response
|
| 142 |
lyrics = response['answer']
|
| 143 |
st.markdown(f"```\n{lyrics}\n```")
|
| 144 |
st.session_state.current_lyrics = lyrics
|
| 145 |
-
|
| 146 |
# Display sources with content
|
| 147 |
with st.expander("View Sources and Context"):
|
| 148 |
st.write("### Top Retrieved Contexts")
|
|
@@ -154,11 +90,11 @@ def main():
|
|
| 154 |
st.write("Content snippet:")
|
| 155 |
st.text(detail['content'])
|
| 156 |
st.write("---")
|
| 157 |
-
|
| 158 |
st.write("\n### All Similar Sources")
|
| 159 |
seen_sources = set()
|
| 160 |
unique_sources = []
|
| 161 |
-
|
| 162 |
for doc, score in response["source_documents_with_scores"]:
|
| 163 |
source_key = (
|
| 164 |
doc.metadata['artist'],
|
|
@@ -167,7 +103,7 @@ def main():
|
|
| 167 |
if source_key not in seen_sources:
|
| 168 |
seen_sources.add(source_key)
|
| 169 |
unique_sources.append((doc, score))
|
| 170 |
-
|
| 171 |
for doc, score in unique_sources:
|
| 172 |
similarity = round((1 - score) * 100, 2)
|
| 173 |
st.write(
|
|
@@ -175,12 +111,12 @@ def main():
|
|
| 175 |
f"{doc.metadata['song_title']} "
|
| 176 |
f"(Similarity: {similarity}%)"
|
| 177 |
)
|
| 178 |
-
|
| 179 |
# Update chat history
|
| 180 |
st.session_state.chat_history.append((user_input, lyrics))
|
| 181 |
-
|
| 182 |
except Exception as e:
|
| 183 |
st.error(f"Error generating lyrics: {str(e)}")
|
| 184 |
|
| 185 |
if __name__ == "__main__":
|
| 186 |
-
main()
|
|
|
|
| 1 |
"""Main Streamlit application for lyric generation."""
|
| 2 |
import os
|
| 3 |
import streamlit as st
|
|
|
|
|
|
|
| 4 |
from pathlib import Path
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
+
# Set environment before other imports
|
| 8 |
+
if os.getenv('DEPLOYMENT_MODE') == 'huggingface':
|
| 9 |
+
os.environ['HF_HOME'] = '/data/.huggingface'
|
| 10 |
+
else:
|
|
|
|
| 11 |
os.environ['DYLD_LIBRARY_PATH'] = '/usr/local/opt/sqlite/lib'
|
| 12 |
|
| 13 |
+
from src.generator.generator import LyricGenerator
|
| 14 |
+
from config.settings import Settings
|
| 15 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def main():
|
| 18 |
"""Main application function"""
|
|
|
|
| 21 |
page_icon="🎵",
|
| 22 |
layout="wide"
|
| 23 |
)
|
| 24 |
+
|
| 25 |
st.title("SongLift LyrGen2")
|
| 26 |
+
|
| 27 |
# Only run startup once per session
|
| 28 |
if 'initialized' not in st.session_state:
|
| 29 |
print("===== Application Startup at", datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "=====\n")
|
| 30 |
|
| 31 |
# Initialize generator
|
| 32 |
try:
|
| 33 |
+
st.info("Initializing generator... this may take a moment.")
|
| 34 |
+
print("\n=== Initializing Generator ===")
|
| 35 |
+
generator = LyricGenerator()
|
| 36 |
+
st.session_state.generator = generator
|
| 37 |
+
st.session_state.chat_history = []
|
| 38 |
+
st.session_state.current_lyrics = None
|
| 39 |
+
st.session_state.initialized = True
|
| 40 |
+
print("Generator initialized successfully")
|
| 41 |
+
st.rerun()
|
| 42 |
except Exception as e:
|
| 43 |
st.error(f"Error initializing generator: {str(e)}")
|
| 44 |
print(f"Error: {str(e)}")
|
| 45 |
import traceback
|
| 46 |
traceback.print_exc()
|
| 47 |
st.stop()
|
| 48 |
+
|
| 49 |
+
# Check OpenAI API key
|
| 50 |
+
if not Settings.OPENAI_API_KEY:
|
| 51 |
+
st.error("OpenAI API key not found. Please set OPENAI_API_KEY.")
|
| 52 |
+
st.stop()
|
| 53 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# Display chat history
|
| 55 |
for message in st.session_state.chat_history:
|
| 56 |
user_msg, assistant_msg = message
|
|
|
|
| 58 |
st.write(user_msg)
|
| 59 |
with st.chat_message("assistant"):
|
| 60 |
st.markdown(f"```\n{assistant_msg}\n```")
|
| 61 |
+
|
| 62 |
# Chat interface
|
| 63 |
+
user_input = st.chat_input("Enter your prompt (ask for new lyrics or modify existing ones)...")
|
| 64 |
+
|
|
|
|
| 65 |
if user_input:
|
| 66 |
with st.chat_message("user"):
|
| 67 |
st.write(user_input)
|
| 68 |
+
|
| 69 |
with st.chat_message("assistant"):
|
| 70 |
try:
|
| 71 |
+
with st.spinner("Generating lyrics..."):
|
| 72 |
response = st.session_state.generator.generate_lyrics(
|
| 73 |
user_input,
|
| 74 |
st.session_state.chat_history
|
| 75 |
)
|
| 76 |
+
|
| 77 |
# Store the response
|
| 78 |
lyrics = response['answer']
|
| 79 |
st.markdown(f"```\n{lyrics}\n```")
|
| 80 |
st.session_state.current_lyrics = lyrics
|
| 81 |
+
|
| 82 |
# Display sources with content
|
| 83 |
with st.expander("View Sources and Context"):
|
| 84 |
st.write("### Top Retrieved Contexts")
|
|
|
|
| 90 |
st.write("Content snippet:")
|
| 91 |
st.text(detail['content'])
|
| 92 |
st.write("---")
|
| 93 |
+
|
| 94 |
st.write("\n### All Similar Sources")
|
| 95 |
seen_sources = set()
|
| 96 |
unique_sources = []
|
| 97 |
+
|
| 98 |
for doc, score in response["source_documents_with_scores"]:
|
| 99 |
source_key = (
|
| 100 |
doc.metadata['artist'],
|
|
|
|
| 103 |
if source_key not in seen_sources:
|
| 104 |
seen_sources.add(source_key)
|
| 105 |
unique_sources.append((doc, score))
|
| 106 |
+
|
| 107 |
for doc, score in unique_sources:
|
| 108 |
similarity = round((1 - score) * 100, 2)
|
| 109 |
st.write(
|
|
|
|
| 111 |
f"{doc.metadata['song_title']} "
|
| 112 |
f"(Similarity: {similarity}%)"
|
| 113 |
)
|
| 114 |
+
|
| 115 |
# Update chat history
|
| 116 |
st.session_state.chat_history.append((user_input, lyrics))
|
| 117 |
+
|
| 118 |
except Exception as e:
|
| 119 |
st.error(f"Error generating lyrics: {str(e)}")
|
| 120 |
|
| 121 |
if __name__ == "__main__":
|
| 122 |
+
main()
|