Spaces:
No application file
No application file
Download Main api from johanore/Mpmusic: direct link, hf CLI and curl.
- Browser
- Download file 8.38 kB
-
https://huggingface.co/spaces/johanore/Mpmusic/resolve/main/Main%20api
- Command line
-
hf download 'hf://spaces/johanore/Mpmusic/Main api'
-
curl -L -o 'Main api' https://huggingface.co/spaces/johanore/Mpmusic/resolve/main/Main%20api
8.38 kB
| import gradio as gr | |
| import torch | |
| from transformers import AutoProcessor, MusicgenForConditionalGeneration | |
| import scipy.io.wavfile | |
| import numpy as np | |
| import base64 | |
| import io | |
| import json | |
| import os | |
| from datetime import datetime | |
| print("=" * 50) | |
| print("AI Music Studio API - Starting up...") | |
| print("=" * 50) | |
| # Model cache | |
| models = {} | |
| PROCESSOR = None | |
| MODEL = None | |
| DEVICE = None | |
| def load_model(model_name="facebook/musicgen-medium"): | |
| """Load or retrieve cached model""" | |
| global PROCESSOR, MODEL, DEVICE | |
| if MODEL is not None: | |
| return True | |
| try: | |
| print(f"Loading {model_name}...") | |
| PROCESSOR = AutoProcessor.from_pretrained(model_name) | |
| MODEL = MusicgenForConditionalGeneration.from_pretrained(model_name) | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| MODEL = MODEL.to(DEVICE) | |
| MODEL.eval() | |
| param_count = sum(p.numel() for p in MODEL.parameters()) / 1e9 | |
| print(f"β Model loaded: {param_count:.1f}B parameters on {DEVICE}") | |
| return True | |
| except Exception as e: | |
| print(f"β Model load failed: {e}") | |
| return False | |
| def generate_section(prompt, duration, guidance=3.0, temperature=1.0, prev_audio=None): | |
| """Generate a single section of music""" | |
| global PROCESSOR, MODEL, DEVICE | |
| max_tokens = int(duration) * 50 | |
| # Build conditioning if previous audio exists | |
| if prev_audio is not None: | |
| inputs = PROCESSOR( | |
| audio=prev_audio, | |
| text=[prompt], | |
| padding=True, | |
| return_tensors="pt", | |
| ).to(DEVICE) | |
| else: | |
| inputs = PROCESSOR( | |
| text=[prompt], | |
| padding=True, | |
| return_tensors="pt", | |
| ).to(DEVICE) | |
| with torch.no_grad(): | |
| audio_values = MODEL.generate( | |
| **inputs, | |
| max_new_tokens=max_tokens, | |
| guidance_scale=guidance, | |
| temperature=temperature, | |
| do_sample=True, | |
| ) | |
| audio_data = audio_values[0, 0].cpu().numpy() | |
| sr = MODEL.config.audio_encoder.sampling_rate | |
| return np.clip(audio_data, -1.0, 1.0), sr | |
| def crossfade(audio1, audio2, sr, overlap_seconds=2): | |
| """Smooth crossfade between two audio segments""" | |
| overlap_samples = int(overlap_seconds * sr) | |
| if len(audio1) < overlap_samples or len(audio2) < overlap_samples: | |
| return np.concatenate([audio1, audio2]) | |
| fade_out = np.linspace(1, 0, overlap_samples) | |
| fade_in = np.linspace(0, 1, overlap_samples) | |
| combined = np.concatenate([ | |
| audio1[:-overlap_samples], | |
| audio1[-overlap_samples:] * fade_out + audio2[:overlap_samples] * fade_in, | |
| audio2[overlap_samples:] | |
| ]) | |
| return combined | |
| def generate_music(prompt, duration, model_choice, structure_json, guidance, temperature): | |
| """ | |
| Main generation function with structure support | |
| Returns base64 encoded audio | |
| """ | |
| try: | |
| # Load model | |
| if not load_model(model_choice): | |
| return "Error: Failed to load model", None | |
| # Parse structure | |
| try: | |
| structure = json.loads(structure_json) if structure_json else [{"name": "Full", "duration": int(duration), "desc": ""}] | |
| except: | |
| structure = [{"name": "Full", "duration": int(duration), "desc": ""}] | |
| print(f"Generating with structure: {[s['name'] for s in structure]}") | |
| # Generate each section | |
| all_audio = [] | |
| sr = None | |
| for i, section in enumerate(structure): | |
| print(f"Generating section {i+1}/{len(structure)}: {section['name']}") | |
| # Build full prompt | |
| full_prompt = f"{prompt}. {section['desc']}".strip() | |
| section_duration = section['duration'] | |
| # Add overlap for crossfade (except first) | |
| gen_duration = section_duration + (2 if i > 0 else 0) | |
| # Generate | |
| audio, sr = generate_section(full_prompt, gen_duration, guidance, temperature, | |
| all_audio[-1] if all_audio else None) | |
| # Crossfade with previous | |
| if all_audio: | |
| audio = crossfade(all_audio[-1], audio, sr, 2) | |
| all_audio[-1] = audio # Replace with crossfaded version | |
| else: | |
| all_audio.append(audio) | |
| # Final audio is the last (fully crossfaded) segment | |
| final_audio = all_audio[-1] | |
| # Trim to exact total duration | |
| total_duration = sum(s['duration'] for s in structure) | |
| target_samples = int(total_duration * sr) | |
| if len(final_audio) > target_samples: | |
| final_audio = final_audio[:target_samples] | |
| # Normalize | |
| final_audio = np.clip(final_audio, -1.0, 1.0) | |
| if np.max(np.abs(final_audio)) > 0: | |
| final_audio = final_audio / np.max(np.abs(final_audio)) * 0.95 | |
| # Convert to WAV bytes then base64 | |
| buffer = io.BytesIO() | |
| scipy.io.wavfile.write(buffer, sr, (final_audio * 32767).astype(np.int16)) | |
| buffer.seek(0) | |
| audio_b64 = base64.b64encode(buffer.read()).decode('utf-8') | |
| # Also create file for Gradio audio output | |
| output_path = "/tmp/generated_music.wav" | |
| scipy.io.wavfile.write(output_path, sr, (final_audio * 32767).astype(np.int16)) | |
| print(f"β Generation complete: {total_duration}s @ {sr}Hz") | |
| return audio_b64, output_path | |
| except Exception as e: | |
| print(f"β Generation error: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return f"Error: {str(e)}", None | |
| # Load model on startup | |
| print("Pre-loading model...") | |
| load_model() | |
| # Create Gradio interface | |
| with gr.Blocks(title="AI Music Studio API") as demo: | |
| gr.Markdown(""" | |
| # π΅ AI Music Studio API | |
| Backend service for web music generation. Use the API endpoint for programmatic access. | |
| **API Endpoint:** `/api/predict` | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| prompt = gr.Textbox( | |
| label="Music Prompt", | |
| placeholder="e.g., Epic orchestral soundtrack with thunderous drums", | |
| lines=2 | |
| ) | |
| duration = gr.Slider(5, 30, 10, step=1, label="Duration per section (seconds)") | |
| model = gr.Dropdown( | |
| choices=[ | |
| "facebook/musicgen-small", | |
| "facebook/musicgen-medium", | |
| "facebook/musicgen-large", | |
| "facebook/musicgen-melody" | |
| ], | |
| value="facebook/musicgen-medium", | |
| label="Model" | |
| ) | |
| structure = gr.Textbox( | |
| label="Structure JSON", | |
| placeholder='[{"name": "Intro", "duration": 10, "desc": "quiet start"}]', | |
| value="", | |
| visible=False # Hidden, used via API | |
| ) | |
| guidance = gr.Slider(1.0, 10.0, 3.0, step=0.5, label="Guidance Scale") | |
| temperature = gr.Slider(0.1, 2.0, 1.0, step=0.1, label="Temperature") | |
| generate_btn = gr.Button("π Generate", variant="primary") | |
| with gr.Column(): | |
| audio_output = gr.Audio(label="Generated Music", type="filepath") | |
| base64_output = gr.Textbox( | |
| label="Base64 Output (for API)", | |
| lines=3, | |
| max_lines=5 | |
| ) | |
| generate_btn.click( | |
| fn=generate_music, | |
| inputs=[prompt, duration, model, structure, guidance, temperature], | |
| outputs=[base64_output, audio_output] | |
| ) | |
| gr.Markdown(""" | |
| ### API Usage Example | |
| ```python | |
| import requests | |
| response = requests.post( | |
| "https://your-username-musicgen-api.hf.space/api/predict", | |
| json={ | |
| "data": [ | |
| "Epic orchestral music", | |
| 10, | |
| "facebook/musicgen-medium", | |
| '[{"name": "Full", "duration": 10, "desc": ""}]', | |
| 3.0, | |
| 1.0 | |
| ] | |
| } | |
| ) | |
| audio_b64 = response.json()["data"][0] | |
| ``` | |
| """) | |
| if __name__ == "__main__": | |
| demo.launch() |