Phoenixak99 commited on
Commit
8f377cf
Β·
verified Β·
1 Parent(s): 1a4b8ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -154
app.py CHANGED
@@ -322,15 +322,30 @@ def time_post_request(api_url, headers=None, payload=None, timeout=None):
322
 
323
  return response
324
 
325
- def generate_audio(genre, energy_level, tempo, description, duration):
326
- # Create placeholders for dynamic updates
327
- status_placeholder = st.empty()
328
- progress_placeholder = st.empty()
329
- subscription_info_placeholder = st.empty()
330
- server_message_placeholder = st.empty()
331
- stage_message_placeholder = st.empty()
 
 
 
 
 
 
332
 
333
- # Define the subscription tiers information
 
 
 
 
 
 
 
 
 
334
  subscription_info = """
335
  ### πŸ“‹ **Subscription Tiers**
336
 
@@ -355,173 +370,131 @@ def generate_audio(genre, energy_level, tempo, description, duration):
355
  significantly reducing wait times from 7 minutes to just 30 seconds!
356
  """
357
 
358
- # Start server warmup with an initial request
359
- warmup_payload = {"inputs": {"prompt": "warmup", "duration": 1}}
360
- api_headers = get_api_headers()
361
-
362
- # Create a thread for the initial warmup request
363
- def make_warmup_request():
364
- try:
365
- return time_post_request(API_URL, headers=api_headers, payload=warmup_payload, timeout=600)
366
- except:
367
- return None
368
-
369
- warmup_thread = threading.Thread(target=make_warmup_request)
370
- warmup_thread.start()
371
-
372
- # Start the countdown while server is warming up
373
  start_time = time.time()
374
- total_warmup_time = 420 # 7 minutes in seconds
375
-
376
- # Define server initialization stages
377
- stages = [
378
- {"time": 0, "message": "πŸš€ Initializing server resources..."},
379
- {"time": 60, "message": "βš™οΈ Loading AI models into memory..."},
380
- {"time": 180, "message": "πŸ”§ Optimizing model parameters..."},
381
- {"time": 300, "message": "πŸ“Š Configuring generation settings..."},
382
- {"time": 360, "message": "✨ Finalizing server preparation..."}
383
- ]
384
  current_stage = 0
385
-
386
- while time.time() - start_time < total_warmup_time and warmup_thread.is_alive():
387
  elapsed = time.time() - start_time
388
  remaining = total_warmup_time - elapsed
389
  progress = elapsed / total_warmup_time
390
 
391
- # Update current stage based on elapsed time
392
  while current_stage < len(stages) - 1 and elapsed > stages[current_stage + 1]["time"]:
393
  current_stage += 1
394
-
395
  minutes_remaining = int(remaining // 60)
396
  seconds_remaining = int(remaining % 60)
397
 
 
398
  status_placeholder.markdown("### πŸ”„ AI Server Initialization in Progress")
399
  progress_placeholder.progress(progress)
400
-
401
- stage_message_placeholder.info(stages[current_stage]["message"])
402
-
403
- server_message_placeholder.warning(
404
  f"⏳ Estimated time remaining: {minutes_remaining}m {seconds_remaining}s\n\n"
405
- f"🎡 Free tier server initialization takes about 7 minutes\n\n"
406
  "πŸ’‘ Premium users enjoy dramatically faster startup times (30s or less)!"
407
  )
408
-
409
  subscription_info_placeholder.markdown(subscription_info)
 
 
 
 
 
 
410
  time.sleep(0.1)
411
-
412
- # Clear initialization messages
413
- status_placeholder.empty()
414
- progress_placeholder.empty()
415
- stage_message_placeholder.empty()
416
- server_message_placeholder.empty()
417
-
418
- # Check if the user is logged in
419
- if st.session_state.get("jwt_token") is None:
420
- st.error("You must be logged in to generate audio.")
421
- return
422
-
423
- # Headers for authenticated requests to your WordPress site
424
- auth_headers = get_auth_headers()
425
-
426
- # Get user ID
427
- user_id_url = "https://songlabai.com/wp-json/custom-api/v1/current-user-id"
428
- user_response = requests.get(user_id_url, headers=auth_headers)
429
- if user_response.status_code != 200:
430
- st.error("Failed to retrieve your user information.")
431
- return
432
-
433
- user_data = user_response.json()
434
- user_id = user_data["user_id"]
435
-
436
- # Get subscription status
437
- subscription_url = "https://songlabai.com/wp-json/custom-api/v1/subscription"
438
- subscription_response = requests.get(subscription_url, headers=auth_headers)
439
- if subscription_response.status_code != 200:
440
- st.error("Failed to retrieve your subscription status.")
441
- return
442
-
443
- subscription_data = subscription_response.json()
444
- subscription_plan_id = subscription_data["subscription_plan_id"]
445
- has_exceeded_generation_limit = subscription_data["has_exceeded_generation_limit"]
446
-
447
- # Check subscription plan and limits
448
- if has_exceeded_generation_limit:
449
- st.error(
450
- "You have reached your generation limit. "
451
- "Please upgrade your subscription for additional access."
452
- " [Upgrade Now](https://songlabai.com/subscribe/)"
453
- )
454
- return
455
-
456
- # Prepare the prompt and payload for the music generation API
457
- prompt = f"Genre: {genre}, Energy Level: {energy_level}, Tempo: {tempo}, Description: {description}"
458
- payload = {"inputs": {"prompt": prompt, "duration": duration}}
459
-
460
- # Enhanced retry logic with better feedback
461
- max_retries = 3
462
- retry_delay = 30 # increased initial delay
463
- for attempt in range(max_retries):
464
- current_delay = retry_delay * (attempt + 1) # Progressive delay
465
 
466
- with st.spinner(f"Generating audio... Attempt {attempt+1}/{max_retries}"):
467
- try:
468
- response = time_post_request(API_URL, headers=api_headers, payload=payload, timeout=600)
469
-
470
- if response is None:
471
- server_message_placeholder.warning(
472
- "πŸ”„ Finalizing server preparation. "
473
- f"Retrying in {current_delay} seconds... \n\n"
474
- "πŸ’‘ Premium subscribers enjoy faster access with dedicated servers!"
475
- )
476
- time.sleep(current_delay)
477
- continue
478
-
479
- if response.status_code == 200:
480
- placeholder1 = st.empty()
481
- placeholder1.success("βœ”οΈ Audio Generated, Loading...")
482
- load_and_play_generated_audio(response)
483
- placeholder1.empty()
484
-
485
- # Update generation count
486
- update_generation_url = "https://songlabai.com/wp-json/custom-api/v1/update-generation-count"
487
- update_response = requests.post(update_generation_url, headers=auth_headers)
488
- if update_response.status_code != 200:
489
- st.error("Failed to update your generation count.")
490
-
491
- # Check if the user has now exceeded the limit
492
- subscription_status_url = "https://songlabai.com/wp-json/custom-api/v1/subscription"
493
- subscription_response = requests.get(subscription_status_url, headers=auth_headers)
494
- if subscription_response.status_code == 200:
495
- subscription_data = subscription_response.json()
496
- if subscription_data["has_exceeded_generation_limit"]:
497
- st.error(
498
- "You have reached your generation limit. "
499
- "Please upgrade your subscription for additional access."
500
- " [Upgrade Now](https://songlabai.com/subscribe/)"
501
- )
502
- return
503
- else:
504
- server_message_placeholder.warning(
505
- f"⚠️ Attempt {attempt+1} failed with status code {response.status_code}. "
506
- f"Retrying in {current_delay} seconds...\n\n"
507
- "πŸ’‘ Premium users experience fewer delays and faster generation times!"
508
- )
509
- time.sleep(current_delay)
510
 
511
- except requests.exceptions.Timeout:
512
- server_message_placeholder.warning(
513
- "⏱️ Request timed out while server is initializing.\n\n"
514
- "πŸ’‘ Premium subscribers get priority access to ready servers!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
  )
516
- time.sleep(current_delay)
517
- continue
518
-
519
- # If all retries failed
520
- st.error(
521
- "❌ Failed to generate audio after multiple attempts.\n\n"
522
- "Consider upgrading to premium for better server availability and faster generation times.\n\n"
523
- "[Upgrade Now](https://songlabai.com/subscribe/)"
524
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
 
526
  def download_audio():
527
  if st_state.audio_pydub is None:
 
322
 
323
  return response
324
 
325
+ def check_server_status():
326
+ """Check if the server is warm by making a minimal request"""
327
+ warmup_payload = {"inputs": {"prompt": "warmup", "duration": 1}}
328
+ try:
329
+ response = time_post_request(
330
+ API_URL,
331
+ headers=get_api_headers(),
332
+ payload=warmup_payload,
333
+ timeout=10 # Short timeout for quick check
334
+ )
335
+ return response is not None and response.status_code == 200
336
+ except:
337
+ return False
338
 
339
+ def wait_for_server_warmup(status_placeholder, progress_placeholder, subscription_info_placeholder, stage_placeholder):
340
+ """Handle server warmup with detailed progress stages"""
341
+ stages = [
342
+ {"time": 0, "message": "πŸš€ Initializing server resources..."},
343
+ {"time": 60, "message": "βš™οΈ Loading AI models into memory..."},
344
+ {"time": 180, "message": "πŸ”§ Optimizing model parameters..."},
345
+ {"time": 300, "message": "πŸ“Š Configuring generation settings..."},
346
+ {"time": 360, "message": "✨ Finalizing server preparation..."}
347
+ ]
348
+
349
  subscription_info = """
350
  ### πŸ“‹ **Subscription Tiers**
351
 
 
370
  significantly reducing wait times from 7 minutes to just 30 seconds!
371
  """
372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  start_time = time.time()
374
+ total_warmup_time = 420 # 7 minutes
 
 
 
 
 
 
 
 
 
375
  current_stage = 0
376
+
377
+ while time.time() - start_time < total_warmup_time:
378
  elapsed = time.time() - start_time
379
  remaining = total_warmup_time - elapsed
380
  progress = elapsed / total_warmup_time
381
 
382
+ # Update current stage
383
  while current_stage < len(stages) - 1 and elapsed > stages[current_stage + 1]["time"]:
384
  current_stage += 1
385
+
386
  minutes_remaining = int(remaining // 60)
387
  seconds_remaining = int(remaining % 60)
388
 
389
+ # Update UI
390
  status_placeholder.markdown("### πŸ”„ AI Server Initialization in Progress")
391
  progress_placeholder.progress(progress)
392
+ stage_placeholder.info(
393
+ f"{stages[current_stage]['message']}\n\n"
 
 
394
  f"⏳ Estimated time remaining: {minutes_remaining}m {seconds_remaining}s\n\n"
 
395
  "πŸ’‘ Premium users enjoy dramatically faster startup times (30s or less)!"
396
  )
 
397
  subscription_info_placeholder.markdown(subscription_info)
398
+
399
+ # Check if server is ready every 30 seconds
400
+ if elapsed % 30 == 0:
401
+ if check_server_status():
402
+ return True
403
+
404
  time.sleep(0.1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
 
406
+ return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
 
408
+ def generate_audio(genre, energy_level, tempo, description, duration):
409
+ # Create placeholders
410
+ status_placeholder = st.empty()
411
+ progress_placeholder = st.empty()
412
+ subscription_placeholder = st.empty()
413
+ stage_placeholder = st.empty()
414
+
415
+ try:
416
+ # First, verify user is logged in and has permissions
417
+ if st.session_state.get("jwt_token") is None:
418
+ st.error("You must be logged in to generate audio.")
419
+ return
420
+
421
+ auth_headers = get_auth_headers()
422
+
423
+ # Check subscription status
424
+ subscription_url = "https://songlabai.com/wp-json/custom-api/v1/subscription"
425
+ subscription_response = requests.get(subscription_url, headers=auth_headers)
426
+ if subscription_response.status_code != 200:
427
+ st.error("Failed to retrieve your subscription status.")
428
+ return
429
+
430
+ subscription_data = subscription_response.json()
431
+ if subscription_data["has_exceeded_generation_limit"]:
432
+ st.error(
433
+ "You have reached your generation limit. "
434
+ "Please upgrade your subscription for additional access."
435
+ " [Upgrade Now](https://songlabai.com/subscribe/)"
436
+ )
437
+ return
438
+
439
+ # Check if server is cold
440
+ if not check_server_status():
441
+ status_placeholder.warning(
442
+ "πŸ”„ Server needs to warm up. This may take up to 7 minutes for free users.\n\n"
443
+ "πŸ’‘ Premium users enjoy much faster startup times!"
444
+ )
445
+
446
+ # Wait for server to warm up with progress display
447
+ server_ready = wait_for_server_warmup(
448
+ status_placeholder,
449
+ progress_placeholder,
450
+ subscription_placeholder,
451
+ stage_placeholder
452
+ )
453
+
454
+ if not server_ready:
455
+ st.error(
456
+ "❌ Server initialization timed out.\n\n"
457
+ "Consider upgrading to premium for reliable, fast access.\n\n"
458
+ "[Upgrade Now](https://songlabai.com/subscribe/)"
459
  )
460
+ return
461
+
462
+ # Clear warmup messages
463
+ for placeholder in [status_placeholder, progress_placeholder, subscription_placeholder, stage_placeholder]:
464
+ placeholder.empty()
465
+
466
+ # Prepare generation request
467
+ prompt = f"Genre: {genre}, Energy Level: {energy_level}, Tempo: {tempo}, Description: {description}"
468
+ payload = {"inputs": {"prompt": prompt, "duration": duration}}
469
+ api_headers = get_api_headers()
470
+
471
+ # Make the generation request
472
+ with st.spinner("🎡 Generating your music..."):
473
+ response = time_post_request(API_URL, headers=api_headers, payload=payload, timeout=600)
474
+
475
+ if response and response.status_code == 200:
476
+ st.success("✨ Music generated successfully!")
477
+ load_and_play_generated_audio(response)
478
+
479
+ # Update generation count
480
+ update_generation_url = "https://songlabai.com/wp-json/custom-api/v1/update-generation-count"
481
+ requests.post(update_generation_url, headers=auth_headers)
482
+ else:
483
+ st.error(
484
+ "❌ Failed to generate audio.\n\n"
485
+ "This might be due to high server load. Premium users experience fewer failures.\n\n"
486
+ "[Upgrade Now](https://songlabai.com/subscribe/)"
487
+ )
488
+
489
+ except Exception as e:
490
+ st.error(
491
+ f"An error occurred: {str(e)}\n\n"
492
+ "Please try again or consider upgrading for more reliable service."
493
+ )
494
+ finally:
495
+ # Clean up any remaining placeholders
496
+ for placeholder in [status_placeholder, progress_placeholder, subscription_placeholder, stage_placeholder]:
497
+ placeholder.empty()
498
 
499
  def download_audio():
500
  if st_state.audio_pydub is None: