Update app.py
Browse files
app.py
CHANGED
|
@@ -6,81 +6,53 @@ import gradio as gr
|
|
| 6 |
logging.basicConfig(level=logging.INFO)
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
def setup_modal_authentication():
|
| 11 |
-
"""Configure Modal authentication properly"""
|
| 12 |
-
modal_token = os.environ.get("MODAL_TOKEN")
|
| 13 |
-
|
| 14 |
-
if not modal_token:
|
| 15 |
-
logger.warning("β οΈ MODAL_TOKEN environment variable not found")
|
| 16 |
-
return False
|
| 17 |
-
|
| 18 |
-
# Set multiple environment variables that Modal might check
|
| 19 |
-
try:
|
| 20 |
-
# Method 1: Set MODAL_TOKEN_ID (most common)
|
| 21 |
-
os.environ["MODAL_TOKEN_ID"] = modal_token
|
| 22 |
-
|
| 23 |
-
# Method 2: Set MODAL_TOKEN_SECRET (alternative)
|
| 24 |
-
os.environ["MODAL_TOKEN_SECRET"] = modal_token
|
| 25 |
-
|
| 26 |
-
# Method 3: Set the base MODAL_TOKEN (redundant but safe)
|
| 27 |
-
os.environ["MODAL_TOKEN"] = modal_token
|
| 28 |
-
|
| 29 |
-
logger.info("β
Modal environment variables configured")
|
| 30 |
-
return True
|
| 31 |
-
|
| 32 |
-
except Exception as e:
|
| 33 |
-
logger.error(f"β Failed to configure Modal environment: {e}")
|
| 34 |
-
return False
|
| 35 |
-
|
| 36 |
-
# Check Modal availability with robust authentication
|
| 37 |
MODAL_AVAILABLE = False
|
| 38 |
generate_content_with_llm = None
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
try:
|
| 47 |
-
#
|
| 48 |
generate_content_with_llm = modal.Function.from_name(
|
| 49 |
"content-creation-agent",
|
| 50 |
"generate_content_with_llm"
|
| 51 |
)
|
| 52 |
|
| 53 |
-
# Test
|
| 54 |
health_check_func = modal.Function.from_name(
|
| 55 |
"content-creation-agent",
|
| 56 |
"health_check"
|
| 57 |
)
|
| 58 |
|
| 59 |
-
#
|
| 60 |
test_result = health_check_func.remote()
|
| 61 |
-
logger.info(f"β
Modal
|
| 62 |
|
| 63 |
MODAL_AVAILABLE = True
|
| 64 |
-
logger.info("β
Modal successfully connected
|
| 65 |
-
|
| 66 |
-
except Exception as auth_error:
|
| 67 |
-
logger.warning(f"β οΈ Modal authentication failed: {auth_error}")
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
try:
|
| 71 |
generate_content_with_llm = modal.Function.from_name(
|
| 72 |
"content-creation-agent",
|
| 73 |
-
"generate_fallback_content"
|
| 74 |
)
|
| 75 |
MODAL_AVAILABLE = True
|
| 76 |
logger.info("β
Modal connected using fallback function")
|
| 77 |
-
except Exception as
|
| 78 |
-
logger.
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
logger.
|
| 84 |
|
| 85 |
logger.info(f"Modal Status: {'β
Available' if MODAL_AVAILABLE else 'β Unavailable'}")
|
| 86 |
|
|
@@ -90,49 +62,69 @@ def generate_fallback_content(lyrics, artist, title):
|
|
| 90 |
# Analyze lyrics for themes and mood
|
| 91 |
lyrics_lower = lyrics.lower()
|
| 92 |
|
| 93 |
-
#
|
| 94 |
mood = "uplifting"
|
| 95 |
-
if any(word in lyrics_lower for word in ['cry', 'tear', 'pain', 'hurt', 'lost', 'broken', 'sad']):
|
| 96 |
mood = "emotional"
|
| 97 |
-
elif any(word in lyrics_lower for word in ['energy', 'power', 'fire', 'strong', 'fight', 'drive']):
|
| 98 |
mood = "energetic"
|
| 99 |
-
elif any(word in lyrics_lower for word in ['love', 'happy', 'joy', 'hope', 'dream', 'light']):
|
| 100 |
mood = "inspiring"
|
| 101 |
|
| 102 |
-
# Extract themes
|
| 103 |
theme_words = []
|
| 104 |
-
if any(word in lyrics_lower for word in ['love', 'heart', 'romance']):
|
| 105 |
theme_words.append('love')
|
| 106 |
-
if any(word in lyrics_lower for word in ['dream', 'hope', 'future']):
|
| 107 |
theme_words.append('dreams')
|
| 108 |
-
if any(word in lyrics_lower for word in ['night', 'dark', 'star']):
|
| 109 |
theme_words.append('night')
|
| 110 |
-
if any(word in lyrics_lower for word in ['life', 'living', 'journey']):
|
| 111 |
theme_words.append('life')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
themes_text = ', '.join(theme_words[:3]) if theme_words else 'deep emotions'
|
| 114 |
|
| 115 |
-
#
|
| 116 |
genre = 'indie'
|
| 117 |
-
if any(word in lyrics_lower for word in ['rock', 'guitar', 'band', 'drums']):
|
| 118 |
genre = 'rock'
|
| 119 |
-
elif any(word in lyrics_lower for word in ['pop', 'radio', 'catchy', 'dance']):
|
| 120 |
genre = 'pop'
|
| 121 |
-
elif any(word in lyrics_lower for word in ['rap', 'flow', 'beats', 'hip']):
|
| 122 |
genre = 'hiphop'
|
| 123 |
-
elif any(word in lyrics_lower for word in ['electronic', 'synth', 'edm']):
|
| 124 |
genre = 'electronic'
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
|
| 128 |
-
'youtube': f
|
| 129 |
-
'twitter': f
|
| 130 |
-
'instagram': f
|
| 131 |
-
'facebook': f
|
| 132 |
-
'minds':
|
| 133 |
-
'gab':
|
| 134 |
}
|
| 135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
artist_display = artist if artist.strip() else "Anonymous Artist"
|
| 137 |
by_artist = f" - {artist_display}" if artist.strip() else ""
|
| 138 |
|
|
@@ -197,7 +189,7 @@ Give it a listen and support independent creators!
|
|
| 197 |
{hashtags['gab']}"""
|
| 198 |
}
|
| 199 |
else:
|
| 200 |
-
# Anonymous content
|
| 201 |
return {
|
| 202 |
'youtube': f"""π΅ {title} π΅
|
| 203 |
|
|
@@ -258,7 +250,7 @@ Give it a listen and support independent creators!
|
|
| 258 |
}
|
| 259 |
|
| 260 |
def generate_all_content(lyrics, artist, title, use_modal):
|
| 261 |
-
"""Generate content with Modal toggle
|
| 262 |
if not lyrics.strip() or not title.strip():
|
| 263 |
error_msg = "β Please provide both lyrics and song title"
|
| 264 |
return [""] * 6 + [error_msg]
|
|
@@ -275,12 +267,12 @@ def generate_all_content(lyrics, artist, title, use_modal):
|
|
| 275 |
|
| 276 |
try:
|
| 277 |
if use_modal and MODAL_AVAILABLE and generate_content_with_llm:
|
| 278 |
-
# Try Modal
|
| 279 |
try:
|
| 280 |
logger.info("π Attempting Modal AI generation...")
|
| 281 |
result = generate_content_with_llm.remote(lyrics, artist, title)
|
| 282 |
|
| 283 |
-
# Validate
|
| 284 |
if isinstance(result, dict) and len(result) > 0:
|
| 285 |
content = result
|
| 286 |
status_msg = f"β
Generated with Modal AI in {time.time() - start_time:.2f}s"
|
|
@@ -347,13 +339,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title="π΅ Music Content Creator") as de
|
|
| 347 |
info="The title of your song"
|
| 348 |
)
|
| 349 |
|
| 350 |
-
# Modal toggle
|
| 351 |
modal_toggle = gr.Radio(
|
| 352 |
choices=[
|
| 353 |
("π€ AI Generation (Modal)", True),
|
| 354 |
("π Local Templates", False)
|
| 355 |
],
|
| 356 |
-
value=
|
| 357 |
label="Generation Method",
|
| 358 |
info="Choose between AI-powered generation or local templates"
|
| 359 |
)
|
|
@@ -388,13 +380,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title="π΅ Music Content Creator") as de
|
|
| 388 |
"Here's an example with some sample lyrics\nAbout dreams and aspirations\nReaching for the stars tonight\nNothing's gonna stop this fight\nWe'll keep on climbing higher\nUntil we touch the sky",
|
| 389 |
"", # Empty artist name
|
| 390 |
"Dreams Tonight",
|
| 391 |
-
|
| 392 |
],
|
| 393 |
[
|
| 394 |
"Love is in the air tonight\nHearts beating as one\nDancing under moonlight\nUntil the morning sun\nThis feeling never ends\nLove conquers all",
|
| 395 |
"Romantic Vibes",
|
| 396 |
"Moonlight Dance",
|
| 397 |
-
|
| 398 |
]
|
| 399 |
],
|
| 400 |
inputs=[lyrics_input, artist_input, title_input, modal_toggle],
|
|
@@ -405,12 +397,12 @@ with gr.Blocks(theme=gr.themes.Soft(), title="π΅ Music Content Creator") as de
|
|
| 405 |
gr.Markdown(f"""
|
| 406 |
---
|
| 407 |
**π‘ Tips:**
|
| 408 |
-
- **AI Generation:** Uses GPT-2 on Modal for creative, context-aware content
|
| 409 |
- **Local Templates:** Fast, rule-based generation that always works
|
| 410 |
- **Modal Credits:** Can be used for LLM inference and GPU-intensive functions ([Modal Docs](https://modal.com/docs))
|
| 411 |
- **Best Results:** Include rich, descriptive lyrics for better theme detection
|
| 412 |
|
| 413 |
-
**π§
|
| 414 |
""")
|
| 415 |
|
| 416 |
if __name__ == "__main__":
|
|
|
|
| 6 |
logging.basicConfig(level=logging.INFO)
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
| 9 |
+
# Simplified Modal authentication - no complex setup needed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
MODAL_AVAILABLE = False
|
| 11 |
generate_content_with_llm = None
|
| 12 |
|
| 13 |
+
try:
|
| 14 |
+
import modal
|
| 15 |
+
logger.info(f"Modal version: {modal.__version__}")
|
| 16 |
+
|
| 17 |
+
# Check for Modal token in environment (set by HuggingFace)
|
| 18 |
+
if os.environ.get("MODAL_TOKEN"):
|
| 19 |
try:
|
| 20 |
+
# Try to connect to your Modal functions
|
| 21 |
generate_content_with_llm = modal.Function.from_name(
|
| 22 |
"content-creation-agent",
|
| 23 |
"generate_content_with_llm"
|
| 24 |
)
|
| 25 |
|
| 26 |
+
# Test connection with health check
|
| 27 |
health_check_func = modal.Function.from_name(
|
| 28 |
"content-creation-agent",
|
| 29 |
"health_check"
|
| 30 |
)
|
| 31 |
|
| 32 |
+
# Test if Modal is working
|
| 33 |
test_result = health_check_func.remote()
|
| 34 |
+
logger.info(f"β
Modal health check passed: {test_result}")
|
| 35 |
|
| 36 |
MODAL_AVAILABLE = True
|
| 37 |
+
logger.info("β
Modal successfully connected")
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.warning(f"β οΈ Modal connection failed: {e}")
|
| 41 |
+
# Try fallback function instead
|
| 42 |
try:
|
| 43 |
generate_content_with_llm = modal.Function.from_name(
|
| 44 |
"content-creation-agent",
|
| 45 |
+
"generate_fallback_content"
|
| 46 |
)
|
| 47 |
MODAL_AVAILABLE = True
|
| 48 |
logger.info("β
Modal connected using fallback function")
|
| 49 |
+
except Exception as e2:
|
| 50 |
+
logger.warning(f"β οΈ Modal fallback also failed: {e2}")
|
| 51 |
+
else:
|
| 52 |
+
logger.warning("β οΈ MODAL_TOKEN not found in environment")
|
| 53 |
+
|
| 54 |
+
except ImportError:
|
| 55 |
+
logger.warning("β οΈ Modal package not available")
|
| 56 |
|
| 57 |
logger.info(f"Modal Status: {'β
Available' if MODAL_AVAILABLE else 'β Unavailable'}")
|
| 58 |
|
|
|
|
| 62 |
# Analyze lyrics for themes and mood
|
| 63 |
lyrics_lower = lyrics.lower()
|
| 64 |
|
| 65 |
+
# Advanced mood detection
|
| 66 |
mood = "uplifting"
|
| 67 |
+
if any(word in lyrics_lower for word in ['cry', 'tear', 'pain', 'hurt', 'lost', 'broken', 'sad', 'lonely', 'dark']):
|
| 68 |
mood = "emotional"
|
| 69 |
+
elif any(word in lyrics_lower for word in ['energy', 'power', 'fire', 'strong', 'fight', 'drive', 'force', 'intense']):
|
| 70 |
mood = "energetic"
|
| 71 |
+
elif any(word in lyrics_lower for word in ['love', 'happy', 'joy', 'hope', 'dream', 'light', 'beautiful', 'amazing']):
|
| 72 |
mood = "inspiring"
|
| 73 |
|
| 74 |
+
# Extract themes with better detection
|
| 75 |
theme_words = []
|
| 76 |
+
if any(word in lyrics_lower for word in ['love', 'heart', 'romance', 'kiss', 'together']):
|
| 77 |
theme_words.append('love')
|
| 78 |
+
if any(word in lyrics_lower for word in ['dream', 'hope', 'future', 'tomorrow', 'vision']):
|
| 79 |
theme_words.append('dreams')
|
| 80 |
+
if any(word in lyrics_lower for word in ['night', 'dark', 'star', 'moon', 'midnight']):
|
| 81 |
theme_words.append('night')
|
| 82 |
+
if any(word in lyrics_lower for word in ['life', 'living', 'journey', 'path', 'way']):
|
| 83 |
theme_words.append('life')
|
| 84 |
+
if any(word in lyrics_lower for word in ['freedom', 'free', 'escape', 'break', 'liberation']):
|
| 85 |
+
theme_words.append('freedom')
|
| 86 |
+
if any(word in lyrics_lower for word in ['time', 'moment', 'forever', 'always', 'memory']):
|
| 87 |
+
theme_words.append('time')
|
| 88 |
|
| 89 |
themes_text = ', '.join(theme_words[:3]) if theme_words else 'deep emotions'
|
| 90 |
|
| 91 |
+
# Advanced genre detection
|
| 92 |
genre = 'indie'
|
| 93 |
+
if any(word in lyrics_lower for word in ['rock', 'guitar', 'band', 'drums', 'electric', 'amp']):
|
| 94 |
genre = 'rock'
|
| 95 |
+
elif any(word in lyrics_lower for word in ['pop', 'radio', 'catchy', 'dance', 'party', 'club']):
|
| 96 |
genre = 'pop'
|
| 97 |
+
elif any(word in lyrics_lower for word in ['rap', 'flow', 'beats', 'hip', 'street', 'rhyme']):
|
| 98 |
genre = 'hiphop'
|
| 99 |
+
elif any(word in lyrics_lower for word in ['electronic', 'synth', 'edm', 'techno', 'digital']):
|
| 100 |
genre = 'electronic'
|
| 101 |
+
elif any(word in lyrics_lower for word in ['acoustic', 'folk', 'country', 'traditional']):
|
| 102 |
+
genre = 'acoustic'
|
| 103 |
|
| 104 |
+
# Premium hashtag generation
|
| 105 |
+
base_hashtags = {
|
| 106 |
+
'youtube': [f'{genre}music', 'newmusic', 'musicvideo', f'{mood}music', 'originalmusic', 'independentartist', 'songwriter', 'musicdiscovery', 'viral', 'subscribe', 'newrelease', 'musicproducer', 'instamusic', 'unsignedartist', 'emergingartist'],
|
| 107 |
+
'twitter': [f'{genre}', 'newmusic', 'nowplaying', f'{mood}', 'musicvideo', 'viral'],
|
| 108 |
+
'instagram': [f'{genre}vibes', 'newmusic', 'instamusic', f'{mood}', 'musicpost', 'originalmusic', 'artist', 'viral', 'trending', 'musiclover', 'songwriter', 'independentartist', 'newrelease', 'musicdiscovery', 'vibes'],
|
| 109 |
+
'facebook': [f'{genre}music', 'newmusic', 'originalmusic', f'{mood}', 'musicvideo', 'viral'],
|
| 110 |
+
'minds': ['independentmusic', 'originalmusic', 'newmusic', 'creative', 'authentic'],
|
| 111 |
+
'gab': ['originalmusic', 'independent', 'authentic', 'realmusic', 'newmusic']
|
| 112 |
}
|
| 113 |
|
| 114 |
+
# Add theme-based hashtags
|
| 115 |
+
for platform in base_hashtags:
|
| 116 |
+
for theme in theme_words[:2]: # Add top 2 themes
|
| 117 |
+
base_hashtags[platform].append(f'{theme}music')
|
| 118 |
+
|
| 119 |
+
# Format hashtags with proper limits
|
| 120 |
+
hashtags = {}
|
| 121 |
+
limits = {'youtube': 15, 'instagram': 15, 'twitter': 6, 'facebook': 6, 'minds': 5, 'gab': 5}
|
| 122 |
+
|
| 123 |
+
for platform, tags in base_hashtags.items():
|
| 124 |
+
limit = limits.get(platform, 10)
|
| 125 |
+
formatted_tags = ' '.join(f'#{tag}' for tag in tags[:limit])
|
| 126 |
+
hashtags[platform] = formatted_tags
|
| 127 |
+
|
| 128 |
artist_display = artist if artist.strip() else "Anonymous Artist"
|
| 129 |
by_artist = f" - {artist_display}" if artist.strip() else ""
|
| 130 |
|
|
|
|
| 189 |
{hashtags['gab']}"""
|
| 190 |
}
|
| 191 |
else:
|
| 192 |
+
# Anonymous content
|
| 193 |
return {
|
| 194 |
'youtube': f"""π΅ {title} π΅
|
| 195 |
|
|
|
|
| 250 |
}
|
| 251 |
|
| 252 |
def generate_all_content(lyrics, artist, title, use_modal):
|
| 253 |
+
"""Generate content with Modal toggle"""
|
| 254 |
if not lyrics.strip() or not title.strip():
|
| 255 |
error_msg = "β Please provide both lyrics and song title"
|
| 256 |
return [""] * 6 + [error_msg]
|
|
|
|
| 267 |
|
| 268 |
try:
|
| 269 |
if use_modal and MODAL_AVAILABLE and generate_content_with_llm:
|
| 270 |
+
# Try Modal AI generation
|
| 271 |
try:
|
| 272 |
logger.info("π Attempting Modal AI generation...")
|
| 273 |
result = generate_content_with_llm.remote(lyrics, artist, title)
|
| 274 |
|
| 275 |
+
# Validate result
|
| 276 |
if isinstance(result, dict) and len(result) > 0:
|
| 277 |
content = result
|
| 278 |
status_msg = f"β
Generated with Modal AI in {time.time() - start_time:.2f}s"
|
|
|
|
| 339 |
info="The title of your song"
|
| 340 |
)
|
| 341 |
|
| 342 |
+
# Modal toggle
|
| 343 |
modal_toggle = gr.Radio(
|
| 344 |
choices=[
|
| 345 |
("π€ AI Generation (Modal)", True),
|
| 346 |
("π Local Templates", False)
|
| 347 |
],
|
| 348 |
+
value=MODAL_AVAILABLE, # Default to Modal if available, otherwise local
|
| 349 |
label="Generation Method",
|
| 350 |
info="Choose between AI-powered generation or local templates"
|
| 351 |
)
|
|
|
|
| 380 |
"Here's an example with some sample lyrics\nAbout dreams and aspirations\nReaching for the stars tonight\nNothing's gonna stop this fight\nWe'll keep on climbing higher\nUntil we touch the sky",
|
| 381 |
"", # Empty artist name
|
| 382 |
"Dreams Tonight",
|
| 383 |
+
MODAL_AVAILABLE # Use Modal if available
|
| 384 |
],
|
| 385 |
[
|
| 386 |
"Love is in the air tonight\nHearts beating as one\nDancing under moonlight\nUntil the morning sun\nThis feeling never ends\nLove conquers all",
|
| 387 |
"Romantic Vibes",
|
| 388 |
"Moonlight Dance",
|
| 389 |
+
False # Use local generation
|
| 390 |
]
|
| 391 |
],
|
| 392 |
inputs=[lyrics_input, artist_input, title_input, modal_toggle],
|
|
|
|
| 397 |
gr.Markdown(f"""
|
| 398 |
---
|
| 399 |
**π‘ Tips:**
|
| 400 |
+
- **AI Generation:** Uses GPT-2 on Modal for creative, context-aware content
|
| 401 |
- **Local Templates:** Fast, rule-based generation that always works
|
| 402 |
- **Modal Credits:** Can be used for LLM inference and GPU-intensive functions ([Modal Docs](https://modal.com/docs))
|
| 403 |
- **Best Results:** Include rich, descriptive lyrics for better theme detection
|
| 404 |
|
| 405 |
+
**π§ Status:** {"β
Modal Working" if MODAL_AVAILABLE else "π‘ Local Mode Only"}
|
| 406 |
""")
|
| 407 |
|
| 408 |
if __name__ == "__main__":
|