jasonlawAI79 commited on
Commit
4d49fca
Β·
verified Β·
1 Parent(s): 3509ddd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -29
app.py CHANGED
@@ -6,30 +6,81 @@ import gradio as gr
6
  logging.basicConfig(level=logging.INFO)
7
  logger = logging.getLogger(__name__)
8
 
9
- # Check Modal availability
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
18
- if os.environ.get("MODAL_TOKEN"):
19
  try:
 
20
  generate_content_with_llm = modal.Function.from_name(
21
  "content-creation-agent",
22
  "generate_content_with_llm"
23
  )
 
 
 
 
 
 
 
 
 
 
 
24
  MODAL_AVAILABLE = True
25
- logger.info("βœ… Modal successfully connected")
26
- except Exception as e:
27
- logger.warning(f"⚠️ Modal function loading failed: {e}")
28
- else:
29
- logger.warning("⚠️ MODAL_TOKEN not found in environment")
30
-
31
- except ImportError:
32
- logger.warning("⚠️ Modal package not available")
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  logger.info(f"Modal Status: {'βœ… Available' if MODAL_AVAILABLE else '❌ Unavailable'}")
35
 
@@ -146,7 +197,7 @@ Give it a listen and support independent creators!
146
  {hashtags['gab']}"""
147
  }
148
  else:
149
- # Anonymous content
150
  return {
151
  'youtube': f"""🎡 {title} 🎡
152
 
@@ -207,7 +258,7 @@ Give it a listen and support independent creators!
207
  }
208
 
209
  def generate_all_content(lyrics, artist, title, use_modal):
210
- """Generate content with Modal toggle"""
211
  if not lyrics.strip() or not title.strip():
212
  error_msg = "❌ Please provide both lyrics and song title"
213
  return [""] * 6 + [error_msg]
@@ -224,10 +275,24 @@ def generate_all_content(lyrics, artist, title, use_modal):
224
 
225
  try:
226
  if use_modal and MODAL_AVAILABLE and generate_content_with_llm:
227
- # Try Modal AI generation
228
- result = generate_content_with_llm.remote(lyrics, artist, title)
229
- content = result
230
- status_msg = f"βœ… Generated with Modal AI in {time.time() - start_time:.2f}s"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  else:
232
  # Use local fallback
233
  if use_modal and not MODAL_AVAILABLE:
@@ -237,9 +302,9 @@ def generate_all_content(lyrics, artist, title, use_modal):
237
  status_msg = f"βœ… Generated with local templates in {time.time() - start_time:.2f}s"
238
 
239
  except Exception as e:
240
- logger.warning(f"⚠️ Modal generation failed: {e}")
241
  content = generate_fallback_content(lyrics, artist, title)
242
- status_msg = f"⚠️ Modal failed, used local fallback in {time.time() - start_time:.2f}s"
243
 
244
  # Final yield - actual content for each platform + status
245
  platforms = ['youtube', 'twitter', 'instagram', 'facebook', 'minds', 'gab']
@@ -288,7 +353,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="🎡 Music Content Creator") as de
288
  ("πŸ€– AI Generation (Modal)", True),
289
  ("πŸ“ Local Templates", False)
290
  ],
291
- value=MODAL_AVAILABLE, # Default to Modal if available
292
  label="Generation Method",
293
  info="Choose between AI-powered generation or local templates"
294
  )
@@ -323,13 +388,13 @@ with gr.Blocks(theme=gr.themes.Soft(), title="🎡 Music Content Creator") as de
323
  "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",
324
  "", # Empty artist name
325
  "Dreams Tonight",
326
- True # Use Modal if available
327
  ],
328
  [
329
  "Love is in the air tonight\nHearts beating as one\nDancing under moonlight\nUntil the morning sun\nThis feeling never ends\nLove conquers all",
330
  "Romantic Vibes",
331
  "Moonlight Dance",
332
- False # Use local generation
333
  ]
334
  ],
335
  inputs=[lyrics_input, artist_input, title_input, modal_toggle],
@@ -337,13 +402,15 @@ with gr.Blocks(theme=gr.themes.Soft(), title="🎡 Music Content Creator") as de
337
  )
338
 
339
  # Add footer with info
340
- gr.Markdown("""
341
  ---
342
  **πŸ’‘ Tips:**
343
- - **AI Generation:** Uses GPT-2 on Modal for creative, context-aware content
344
- - **Local Templates:** Fast, rule-based generation that works offline
345
  - **Modal Credits:** Can be used for LLM inference and GPU-intensive functions ([Modal Docs](https://modal.com/docs))
346
  - **Best Results:** Include rich, descriptive lyrics for better theme detection
 
 
347
  """)
348
 
349
  if __name__ == "__main__":
 
6
  logging.basicConfig(level=logging.INFO)
7
  logger = logging.getLogger(__name__)
8
 
9
+ # Robust Modal authentication setup
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
+ if setup_modal_authentication():
41
+ try:
42
+ import modal
43
+ logger.info(f"Modal version: {modal.__version__}")
44
+
45
+ # Try to authenticate and connect
46
  try:
47
+ # Test 1: Try direct function lookup
48
  generate_content_with_llm = modal.Function.from_name(
49
  "content-creation-agent",
50
  "generate_content_with_llm"
51
  )
52
+
53
+ # Test 2: Try a simple health check to verify authentication
54
+ health_check_func = modal.Function.from_name(
55
+ "content-creation-agent",
56
+ "health_check"
57
+ )
58
+
59
+ # Attempt a test call to verify authentication works
60
+ test_result = health_check_func.remote()
61
+ logger.info(f"βœ… Modal authentication test passed: {test_result}")
62
+
63
  MODAL_AVAILABLE = True
64
+ logger.info("βœ… Modal successfully connected and authenticated")
65
+
66
+ except Exception as auth_error:
67
+ logger.warning(f"⚠️ Modal authentication failed: {auth_error}")
68
+
69
+ # Try fallback function
70
+ try:
71
+ generate_content_with_llm = modal.Function.from_name(
72
+ "content-creation-agent",
73
+ "generate_fallback_content" # Use fallback function instead
74
+ )
75
+ MODAL_AVAILABLE = True
76
+ logger.info("βœ… Modal connected using fallback function")
77
+ except Exception as fallback_error:
78
+ logger.error(f"❌ Modal fallback connection failed: {fallback_error}")
79
+
80
+ except ImportError:
81
+ logger.warning("⚠️ Modal package not available")
82
+ else:
83
+ logger.error("❌ Modal authentication setup failed")
84
 
85
  logger.info(f"Modal Status: {'βœ… Available' if MODAL_AVAILABLE else '❌ Unavailable'}")
86
 
 
197
  {hashtags['gab']}"""
198
  }
199
  else:
200
+ # Anonymous content (same structure, different text)
201
  return {
202
  'youtube': f"""🎡 {title} 🎡
203
 
 
258
  }
259
 
260
  def generate_all_content(lyrics, artist, title, use_modal):
261
+ """Generate content with Modal toggle and robust error handling"""
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
 
276
  try:
277
  if use_modal and MODAL_AVAILABLE and generate_content_with_llm:
278
+ # Try Modal generation with additional error handling
279
+ try:
280
+ logger.info("πŸ”„ Attempting Modal AI generation...")
281
+ result = generate_content_with_llm.remote(lyrics, artist, title)
282
+
283
+ # Validate the result
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"
287
+ logger.info("βœ… Modal AI generation successful")
288
+ else:
289
+ raise ValueError("Invalid result from Modal function")
290
+
291
+ except Exception as modal_error:
292
+ logger.warning(f"⚠️ Modal AI generation failed: {modal_error}")
293
+ # Fall back to local generation
294
+ content = generate_fallback_content(lyrics, artist, title)
295
+ status_msg = f"⚠️ Modal failed, used local fallback in {time.time() - start_time:.2f}s"
296
  else:
297
  # Use local fallback
298
  if use_modal and not MODAL_AVAILABLE:
 
302
  status_msg = f"βœ… Generated with local templates in {time.time() - start_time:.2f}s"
303
 
304
  except Exception as e:
305
+ logger.error(f"❌ Unexpected error: {e}")
306
  content = generate_fallback_content(lyrics, artist, title)
307
+ status_msg = f"❌ Error occurred, used local fallback in {time.time() - start_time:.2f}s"
308
 
309
  # Final yield - actual content for each platform + status
310
  platforms = ['youtube', 'twitter', 'instagram', 'facebook', 'minds', 'gab']
 
353
  ("πŸ€– AI Generation (Modal)", True),
354
  ("πŸ“ Local Templates", False)
355
  ],
356
+ value=False, # Default to Local to avoid authentication issues
357
  label="Generation Method",
358
  info="Choose between AI-powered generation or local templates"
359
  )
 
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
+ False # Default to local generation
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
+ True # Try Modal if available
398
  ]
399
  ],
400
  inputs=[lyrics_input, artist_input, title_input, modal_toggle],
 
402
  )
403
 
404
  # Add footer with info
405
+ gr.Markdown(f"""
406
  ---
407
  **πŸ’‘ Tips:**
408
+ - **AI Generation:** Uses GPT-2 on Modal for creative, context-aware content {"(Currently experiencing authentication issues)" if not MODAL_AVAILABLE else ""}
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
+ **πŸ”§ Current Status:** Modal connection {"βœ… Working" if MODAL_AVAILABLE else "❌ Authentication Issue - Using Local Generation"}
414
  """)
415
 
416
  if __name__ == "__main__":