ageraustine commited on
Commit
fc3bcbd
·
verified ·
1 Parent(s): 8956c27

rm looping

Browse files
Files changed (1) hide show
  1. app.py +21 -68
app.py CHANGED
@@ -2,15 +2,11 @@ import gradio as gr
2
  import requests
3
  import tempfile
4
  import os
5
- import numpy as np
6
- import soundfile as sf
7
- import librosa
8
  from langchain_openai import ChatOpenAI
9
  from langchain_core.runnables import RunnablePassthrough
10
  from langchain.prompts import PromptTemplate
11
- import math
12
 
13
- # [Previous constants and LangChain setup remains the same...]
14
  MOOD_QUESTIONS = [
15
  "On a scale of 1-5, how would you rate your current energy level?",
16
  "On a scale of 1-5, how would you rate your current stress level?",
@@ -47,43 +43,26 @@ prompt = PromptTemplate(
47
 
48
  music_chain = RunnablePassthrough() | prompt | llm
49
 
50
- def loop_audio(input_path, target_duration=120):
51
- """
52
- Loop the input audio file to reach the target duration using librosa
53
-
54
- Args:
55
- input_path (str): Path to the input audio file
56
- target_duration (int): Desired duration in seconds
57
-
58
- Returns:
59
- str: Path to the looped audio file
60
- """
61
  try:
62
- # Load the audio file
63
- y, sr = librosa.load(input_path, sr=None)
64
-
65
- # Calculate current duration and required loops
66
- current_duration = len(y) / sr
67
- loops_needed = math.ceil(target_duration / current_duration)
68
-
69
- # Create the looped audio
70
- y_looped = np.tile(y, loops_needed)
71
-
72
- # Trim to exact target duration if necessary
73
- target_samples = int(target_duration * sr)
74
- if len(y_looped) > target_samples:
75
- y_looped = y_looped[:target_samples]
76
-
77
- # Save to a new temporary file
78
- with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
79
- sf.write(tmp_file.name, y_looped, sr)
80
- return tmp_file.name
81
-
82
  except Exception as e:
83
- raise Exception(f"Error in audio looping: {str(e)}")
84
 
85
- def generate_music(prompt, duration=120):
86
- """Generate music using the MusicGen API and loop it to the desired duration"""
87
  API_URL = "https://api-inference.huggingface.co/models/facebook/musicgen-small"
88
  headers = {"Authorization": f"Bearer {os.getenv('HF_API_KEY')}"}
89
 
@@ -96,40 +75,14 @@ def generate_music(prompt, duration=120):
96
  if response.status_code != 200:
97
  return None, f"Error: API returned status code {response.status_code}"
98
 
99
- # Save the initial generated audio
100
  with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
101
  tmp_file.write(response.content)
102
- initial_audio_path = tmp_file.name
103
-
104
- # Loop the audio to reach target duration
105
- final_audio_path = loop_audio(initial_audio_path, duration)
106
-
107
- # Clean up the initial audio file
108
- os.unlink(initial_audio_path)
109
 
110
- return final_audio_path, "Music generated and looped successfully!"
111
  except Exception as e:
112
  return None, f"Error: {str(e)}"
113
 
114
- # [Rest of the code remains the same...]
115
- def analyze_mood_and_generate_prompt(responses, preferences):
116
- """Convert questionnaire responses and preferences into a music generation prompt using LangChain"""
117
- try:
118
- prompt_result = music_chain.invoke({
119
- "energy": responses[0],
120
- "stress": responses[1],
121
- "happiness": responses[2],
122
- "current_emotions": responses[3],
123
- "desired_mood": responses[4],
124
- "genre": preferences["genre"] or "any",
125
- "instruments": preferences["instruments"] or "any",
126
- "tempo": preferences["tempo"] or "any",
127
- "preferred_mood": preferences["preferred_mood"] or "any"
128
- })
129
- return prompt_result.content
130
- except Exception as e:
131
- return f"Error generating prompt: {str(e)}"
132
-
133
  def gradio_interface(energy, stress, happiness, current_emotions, desired_mood,
134
  genre, instruments, tempo, preferred_mood):
135
  """Main interface function that processes questionnaire and generates music"""
@@ -158,7 +111,7 @@ with gr.Blocks() as demo:
158
  gr.Markdown("""
159
  # Therapeutic Music Generator
160
  Complete the mood assessment questionnaire and optionally specify your musical preferences to receive personalized music
161
- that helps you achieve your desired emotional state. Generated music will be 2 minutes long.
162
  """)
163
 
164
  with gr.Row():
 
2
  import requests
3
  import tempfile
4
  import os
 
 
 
5
  from langchain_openai import ChatOpenAI
6
  from langchain_core.runnables import RunnablePassthrough
7
  from langchain.prompts import PromptTemplate
 
8
 
9
+ # Mood assessment questions
10
  MOOD_QUESTIONS = [
11
  "On a scale of 1-5, how would you rate your current energy level?",
12
  "On a scale of 1-5, how would you rate your current stress level?",
 
43
 
44
  music_chain = RunnablePassthrough() | prompt | llm
45
 
46
+ def analyze_mood_and_generate_prompt(responses, preferences):
47
+ """Convert questionnaire responses and preferences into a music generation prompt using LangChain"""
 
 
 
 
 
 
 
 
 
48
  try:
49
+ prompt_result = music_chain.invoke({
50
+ "energy": responses[0],
51
+ "stress": responses[1],
52
+ "happiness": responses[2],
53
+ "current_emotions": responses[3],
54
+ "desired_mood": responses[4],
55
+ "genre": preferences["genre"] or "any",
56
+ "instruments": preferences["instruments"] or "any",
57
+ "tempo": preferences["tempo"] or "any",
58
+ "preferred_mood": preferences["preferred_mood"] or "any"
59
+ })
60
+ return prompt_result.content
 
 
 
 
 
 
 
 
61
  except Exception as e:
62
+ return f"Error generating prompt: {str(e)}"
63
 
64
+ def generate_music(prompt, duration=10):
65
+ """Generate music using the MusicGen API"""
66
  API_URL = "https://api-inference.huggingface.co/models/facebook/musicgen-small"
67
  headers = {"Authorization": f"Bearer {os.getenv('HF_API_KEY')}"}
68
 
 
75
  if response.status_code != 200:
76
  return None, f"Error: API returned status code {response.status_code}"
77
 
 
78
  with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
79
  tmp_file.write(response.content)
80
+ tmp_file_path = tmp_file.name
 
 
 
 
 
 
81
 
82
+ return tmp_file_path, "Music generated successfully!"
83
  except Exception as e:
84
  return None, f"Error: {str(e)}"
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def gradio_interface(energy, stress, happiness, current_emotions, desired_mood,
87
  genre, instruments, tempo, preferred_mood):
88
  """Main interface function that processes questionnaire and generates music"""
 
111
  gr.Markdown("""
112
  # Therapeutic Music Generator
113
  Complete the mood assessment questionnaire and optionally specify your musical preferences to receive personalized music
114
+ that helps you achieve your desired emotional state.
115
  """)
116
 
117
  with gr.Row():