jacob-c commited on
Commit
0c45734
·
1 Parent(s): afda854
Files changed (1) hide show
  1. app.py +64 -42
app.py CHANGED
@@ -61,12 +61,16 @@ def create_lyrics_prompt(classification_results, song_structure):
61
  main_style = classification_results[0]['label']
62
  secondary_elements = [result['label'] for result in classification_results[1:3]]
63
 
64
- # Create a focused prompt for lyrics generation
65
- prompt = f"""Write lyrics for a song.
66
- Genre: {main_style}
67
- Musical elements: {', '.join(secondary_elements)}
68
 
69
- [Verse 1]"""
 
 
 
 
 
 
70
  return prompt
71
 
72
  def format_lyrics(generated_text, song_structure):
@@ -132,60 +136,78 @@ def generate_lyrics_with_retry(prompt, song_structure, max_retries=5, initial_wa
132
 
133
  for attempt in range(max_retries):
134
  try:
 
 
 
135
  response = requests.post(
136
- "https://api-inference.huggingface.co/models/gpt2", # Using base GPT-2
137
  headers=headers,
138
  json={
139
  "inputs": prompt,
140
  "parameters": {
141
- "max_new_tokens": 150, # Shorter output
142
- "temperature": 0.9, # More creative
143
- "top_k": 50, # Standard top-k sampling
144
  "do_sample": True,
145
  "return_full_text": False,
146
- "num_return_sequences": 3 # Generate multiple sequences
 
147
  }
148
  }
149
  )
150
 
 
 
151
  if response.status_code == 200:
152
- results = response.json()
153
- if not isinstance(results, list) or not results:
154
- continue
155
-
156
- # Try each generated sequence
157
- for result in results:
158
- generated_text = result.get("generated_text", "")
159
- if not generated_text:
160
- continue
161
-
162
- # Basic cleaning
163
- lines = [line.strip() for line in generated_text.split('\n')
164
- if line.strip() and not line.strip().startswith(('[', '#', '`'))]
165
 
166
- # Check if we have enough content
167
- if len(lines) >= 4:
168
- # Format into verses and chorus
169
- formatted_lyrics = []
170
- formatted_lyrics.append("[Verse 1]")
171
- formatted_lyrics.extend(lines[:4])
172
 
173
- if song_structure['choruses'] > 0:
174
- formatted_lyrics.append("\n[Chorus 1]")
175
- formatted_lyrics.extend(lines[4:8] if len(lines) >= 8 else ["..." for _ in range(4)])
176
 
177
- if song_structure['verses'] > 1:
178
- formatted_lyrics.append("\n[Verse 2]")
179
- formatted_lyrics.extend(lines[8:12] if len(lines) >= 12 else ["..." for _ in range(4)])
 
 
 
 
 
180
 
181
- return "\n".join(formatted_lyrics)
182
-
183
- # If we get here, none of the sequences were good enough
184
- if attempt < max_retries - 1:
185
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
  elif response.status_code == 503:
188
- print(f"Model loading, attempt {attempt + 1}/{max_retries}. Waiting {wait_time} seconds...")
189
  time.sleep(wait_time)
190
  wait_time *= 1.5
191
  continue
@@ -196,7 +218,7 @@ def generate_lyrics_with_retry(prompt, song_structure, max_retries=5, initial_wa
196
  return f"Error generating lyrics: {response.text}"
197
 
198
  except Exception as e:
199
- print(f"Error on attempt {attempt + 1}: {str(e)}")
200
  if attempt < max_retries - 1:
201
  time.sleep(wait_time)
202
  wait_time *= 1.5
 
61
  main_style = classification_results[0]['label']
62
  secondary_elements = [result['label'] for result in classification_results[1:3]]
63
 
64
+ # Create a more specific prompt for song lyrics
65
+ prompt = f"""Write a short song with musical elements.
 
 
66
 
67
+ Style: {main_style}
68
+ Elements: {', '.join(secondary_elements)}
69
+
70
+ Start with the first verse:
71
+
72
+ [Verse 1]
73
+ """
74
  return prompt
75
 
76
  def format_lyrics(generated_text, song_structure):
 
136
 
137
  for attempt in range(max_retries):
138
  try:
139
+ print(f"\nAttempt {attempt + 1}: Generating lyrics...")
140
+ print(f"Using prompt:\n{prompt}")
141
+
142
  response = requests.post(
143
+ "https://api-inference.huggingface.co/models/distilgpt2", # Using DistilGPT2 for more reliable generation
144
  headers=headers,
145
  json={
146
  "inputs": prompt,
147
  "parameters": {
148
+ "max_new_tokens": 100, # Shorter output for more focused generation
149
+ "temperature": 0.8,
150
+ "top_p": 0.9,
151
  "do_sample": True,
152
  "return_full_text": False,
153
+ "num_return_sequences": 1, # Single sequence for now
154
+ "stop": ["\n\n", "[End]"]
155
  }
156
  }
157
  )
158
 
159
+ print(f"Response status: {response.status_code}")
160
+
161
  if response.status_code == 200:
162
+ try:
163
+ result = response.json()
164
+ print(f"Raw response: {result}")
 
 
 
 
 
 
 
 
 
 
165
 
166
+ if isinstance(result, list) and len(result) > 0:
167
+ generated_text = result[0].get("generated_text", "")
168
+ if not generated_text:
169
+ print("No text generated, retrying...")
170
+ continue
 
171
 
172
+ # Clean up the generated text
173
+ lines = []
174
+ current_lines = []
175
 
176
+ for line in generated_text.split('\n'):
177
+ line = line.strip()
178
+ if not line or line.startswith(('```', '###', '[')):
179
+ continue
180
+ if len(line.split()) <= 15: # Only include reasonably-sized lines
181
+ current_lines.append(line)
182
+ if len(current_lines) >= 4:
183
+ break
184
 
185
+ if len(current_lines) >= 4:
186
+ # Format into song structure
187
+ lines.append("[Verse 1]")
188
+ lines.extend(current_lines[:4])
189
+
190
+ if song_structure['choruses'] > 0:
191
+ lines.append("\n[Chorus]")
192
+ lines.extend([
193
+ "Let the music play",
194
+ "In our special way",
195
+ "Feel the rhythm flow",
196
+ "As the melodies grow"
197
+ ])
198
+
199
+ return "\n".join(lines)
200
+ else:
201
+ print(f"Not enough valid lines generated (got {len(current_lines)}), retrying...")
202
+ else:
203
+ print("Invalid response format, retrying...")
204
+ except Exception as e:
205
+ print(f"Error processing response: {str(e)}")
206
+ if attempt < max_retries - 1:
207
+ continue
208
 
209
  elif response.status_code == 503:
210
+ print(f"Model loading, waiting {wait_time} seconds...")
211
  time.sleep(wait_time)
212
  wait_time *= 1.5
213
  continue
 
218
  return f"Error generating lyrics: {response.text}"
219
 
220
  except Exception as e:
221
+ print(f"Exception during generation: {str(e)}")
222
  if attempt < max_retries - 1:
223
  time.sleep(wait_time)
224
  wait_time *= 1.5