Phoenixak99 commited on
Commit
0e21a10
·
verified ·
1 Parent(s): 1c43b56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -101
app.py CHANGED
@@ -23,12 +23,53 @@ from wordpress_xmlrpc import Client
23
  from wordpress_xmlrpc.compat import xmlrpc_client
24
  from wordpress_xmlrpc.methods import media
25
 
26
- # Retrieve user_id from query parameters
27
- user_params = st.experimental_get_query_params()
28
- user_id = user_params.get('user_id', [None])[0]
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- # Save user_id in session_state
31
- st.session_state['user_id'] = user_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
 
34
  # Try to get API_URL from environment variables, if not found set to a default value
@@ -273,128 +314,78 @@ def time_post_request(api_url, headers=None, payload=None):
273
 
274
  def generate_audio(genre, energy_level, tempo, description, duration):
275
  count_down = 300
276
- # Check if user_id is present
277
- user_id = st.session_state.get('user_id', None)
278
- if not user_id:
279
- st.error("You need to be logged in to generate audio.")
280
- return
281
-
282
- # Proceed to check the subscription
283
- subscription_api_url = f"https://songlabai.com/wp-json/custom-api/subscription/{user_id}"
284
-
285
- try:
286
- response = requests.get(subscription_api_url)
287
- if response.status_code == 200:
288
- subscription_info = response.json()
289
- subscription_plan_id = subscription_info.get('subscription_plan_id')
290
- has_exceeded_daily_limit = subscription_info.get('has_exceeded_daily_limit', False)
291
-
292
- # Enforce limits based on subscription_plan_id
293
- if subscription_plan_id == '576':
294
- if has_exceeded_daily_limit in [True, 'true', 'True']:
295
- st.error("You have exceeded your daily limit. Please upgrade your plan.")
296
- return
297
- else:
298
- # Proceed to generate audio
299
- pass
300
- elif subscription_plan_id in ['304', '305', '306']:
301
- # User has unlimited generation
302
- pass
303
- else:
304
- st.error("Invalid subscription plan. Please contact support.")
305
- return
306
- else:
307
- st.error("Failed to retrieve your subscription information. Please try again later.")
308
- return
309
- except Exception as e:
310
- st.error(f"An error occurred: {e}")
311
- return
312
  prompt = f"Genre: {genre}, Energy Level: {energy_level}, Tempo: {tempo}, Description: {description},"
313
  payload = {"inputs": {"prompt": prompt, "duration": duration}}
314
  with st.spinner("Generating audio ..."):
315
  response = time_post_request(API_URL, headers, payload)
316
  placeholder1 = st.empty()
317
- if response.status_code != 200:
318
- # Temp Jay Start
 
 
 
 
319
  print(f"Request Headers: {response.request.headers}")
320
  print(f"Request Body: {response.request.body}")
321
  print(f"Response Code: {response.status_code}")
322
  print(f"Response Body: {response.text}")
323
- # Temp Jay End
324
 
325
-
326
- print(str(response.content))
327
  count_down_placeholder = st.empty()
328
  for seconds in range(count_down):
329
  count_down_placeholder.info(
330
- f"The server is currently loading. Retrying in ⏳ {count_down - seconds} seconds."
331
  )
332
  time.sleep(1)
333
  count_down_placeholder.empty()
 
 
334
  with st.spinner("Generating audio ..."):
335
  response = time_post_request(API_URL, headers, payload)
336
- if response.status_code != 200:
337
- count_down_placeholder = st.empty()
338
- for seconds in range(count_down):
339
- count_down_placeholder.info(
340
- f"2nd attempt failed. trying again one more time in ⏳ {count_down - seconds} seconds."
341
- )
342
- time.sleep(1)
343
- count_down_placeholder.empty()
344
- with st.spinner("Generating audio ..."):
345
- response = time_post_request(API_URL, headers, payload)
346
- if response.status_code != 200:
347
- placeholder1.error(
348
- "Failed to generate audio after multiple attempts. Please try again later."
349
- )
350
- else:
351
- placeholder1.success(f"✔️ Audio Generated, Loading...")
352
- load_and_play_generated_audio(response)
353
- placeholder1.empty()
354
- if subscription_plan_id == '576':
355
- update_limit_api_url = f"https://songlabai.com/wp-json/custom-api/update-limit/{user_id}"
356
- try:
357
- update_response = requests.post(update_limit_api_url)
358
- if update_response.status_code == 200:
359
- st.success("Your daily limit has been updated.")
360
- else:
361
- st.error("Failed to update your usage limit. Please try again later.")
362
- except Exception as e:
363
- st.error(f"An error occurred while updating your limit: {e}")
364
- except Exception as e:
365
- st.error(f"An error occurred while updating your limit: {e}")
366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  else:
 
368
  placeholder1.success(f"✔️ Audio Generated, Loading...")
369
  load_and_play_generated_audio(response)
370
  placeholder1.empty()
371
- if subscription_plan_id == '576':
372
- update_limit_api_url = f"https://songlabai.com/wp-json/custom-api/update-limit/{user_id}"
373
- try:
374
- update_response = requests.post(update_limit_api_url)
375
- if update_response.status_code == 200:
376
- st.success("Your daily limit has been updated.")
377
- else:
378
- st.error("Failed to update your usage limit. Please try again later.")
379
- except Exception as e:
380
- st.error(f"An error occurred while updating your limit: {e}")
381
- else:
382
  placeholder1.success(f"✔️ Audio Generated, Loading...")
383
  load_and_play_generated_audio(response)
384
  placeholder1.empty()
385
- if subscription_plan_id == '576':
386
- update_limit_api_url = f"https://songlabai.com/wp-json/custom-api/update-limit/{user_id}"
387
- try:
388
- update_response = requests.post(update_limit_api_url)
389
- if update_response.status_code == 200:
390
- st.success("Your daily limit has been updated.")
391
- else:
392
- st.error("Failed to update your usage limit. Please try again later.")
393
- except Exception as e:
394
- st.error(f"An error occurred while updating your limit: {e}")
395
-
396
-
397
-
398
 
399
  def load_and_play_generated_audio(response):
400
 
 
23
  from wordpress_xmlrpc.compat import xmlrpc_client
24
  from wordpress_xmlrpc.methods import media
25
 
26
+ def get_user_id():
27
+ url = 'https://songlabai.com/wp-json/custom-api/v1/current-user-id-session'
28
+ try:
29
+ response = requests.get(url)
30
+ if response.status_code == 200:
31
+ data = response.json()
32
+ if 'user_id' in data:
33
+ return data['user_id']
34
+ else:
35
+ return None
36
+ else:
37
+ return None
38
+ except Exception as e:
39
+ print(f"Error getting user ID: {e}")
40
+ return None
41
 
42
+ def get_subscription_info(user_id):
43
+ url = f'https://songlabai.com/wp-json/custom-api/subscription/{user_id}'
44
+ try:
45
+ response = requests.get(url)
46
+ if response.status_code == 200:
47
+ data = response.json()
48
+ return data
49
+ else:
50
+ return None
51
+ except Exception as e:
52
+ print(f"Error getting subscription info: {e}")
53
+ return None
54
+
55
+ def update_user_limit(user_id):
56
+ url = f'https://songlabai.com/wp-json/custom-api/update-limit/{user_id}'
57
+ try:
58
+ response = requests.post(url)
59
+ if response.status_code == 200:
60
+ data = response.json()
61
+ if data.get('success') == True:
62
+ print("User limit updated successfully.")
63
+ return True
64
+ else:
65
+ print(f"Failed to update user limit: {data}")
66
+ return False
67
+ else:
68
+ print(f"Failed to update user limit, status code: {response.status_code}")
69
+ return False
70
+ except Exception as e:
71
+ print(f"Error updating user limit: {e}")
72
+ return False
73
 
74
 
75
  # Try to get API_URL from environment variables, if not found set to a default value
 
314
 
315
  def generate_audio(genre, energy_level, tempo, description, duration):
316
  count_down = 300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  prompt = f"Genre: {genre}, Energy Level: {energy_level}, Tempo: {tempo}, Description: {description},"
318
  payload = {"inputs": {"prompt": prompt, "duration": duration}}
319
  with st.spinner("Generating audio ..."):
320
  response = time_post_request(API_URL, headers, payload)
321
  placeholder1 = st.empty()
322
+
323
+ attempt = 1
324
+ max_attempts = 3
325
+ while response.status_code != 200 and attempt < max_attempts:
326
+ # Log the error
327
+ print(f"Attempt {attempt}: Failed to generate audio.")
328
  print(f"Request Headers: {response.request.headers}")
329
  print(f"Request Body: {response.request.body}")
330
  print(f"Response Code: {response.status_code}")
331
  print(f"Response Body: {response.text}")
 
332
 
333
+ # Wait for count_down seconds
 
334
  count_down_placeholder = st.empty()
335
  for seconds in range(count_down):
336
  count_down_placeholder.info(
337
+ f"Attempt {attempt}: The server is currently loading. Retrying in ⏳ {count_down - seconds} seconds."
338
  )
339
  time.sleep(1)
340
  count_down_placeholder.empty()
341
+
342
+ # Try again
343
  with st.spinner("Generating audio ..."):
344
  response = time_post_request(API_URL, headers, payload)
345
+ attempt += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
+ if response.status_code != 200:
348
+ placeholder1.error(
349
+ "Failed to generate audio after multiple attempts. Please try again later."
350
+ )
351
+ return
352
+
353
+ # After successful response (after retries if necessary), perform API checks
354
+
355
+ # Get user ID
356
+ user_id = get_user_id()
357
+ if not user_id:
358
+ st.error("Please log in to generate audio.")
359
+ return
360
+
361
+ # Check subscription via API 2
362
+ subscription_info = get_subscription_info(user_id)
363
+ if not subscription_info:
364
+ st.error("Could not retrieve subscription information.")
365
+ return
366
+
367
+ subscription_plan_id = subscription_info['subscription_plan_id']
368
+ has_exceeded_daily_limit = subscription_info['has_exceeded_daily_limit']
369
+
370
+ if subscription_plan_id == '576':
371
+ if has_exceeded_daily_limit == True:
372
+ st.error("You have reached your daily limit for audio generation.")
373
+ return
374
  else:
375
+ # Allow the user to proceed
376
  placeholder1.success(f"✔️ Audio Generated, Loading...")
377
  load_and_play_generated_audio(response)
378
  placeholder1.empty()
379
+ # After generating audio, update the limit via API 3
380
+ update_user_limit(user_id)
381
+ elif subscription_plan_id in ['304', '305', '306']:
382
+ # Unlimited generation
 
 
 
 
 
 
 
383
  placeholder1.success(f"✔️ Audio Generated, Loading...")
384
  load_and_play_generated_audio(response)
385
  placeholder1.empty()
386
+ else:
387
+ st.error("Your subscription does not allow audio generation.")
388
+ return
 
 
 
 
 
 
 
 
 
 
389
 
390
  def load_and_play_generated_audio(response):
391