Skip to content

bemijonathan/music-service

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dhive AI Music Generator - Refactored

This is a refactored version of the Dhive AI Music Generator with a clean modular structure. The original codebase has been organized into separate modules for better maintainability and code organization.

Project Structure

coding-interview/
├── main.py                     # Main application entry point
├── conf/                       # Configuration module
│   ├── __init__.py
│   └── config.py              # App configuration, database setup, and environment variables
├── models/                     # Database models
│   ├── __init__.py
│   └── song.py                # Song model and SongStatus enum
├── utils/                      # Utility functions and core logic
│   ├── __init__.py
│   ├── helpers.py             # Helper functions for text processing, Cloudinary uploads, etc.
│   ├── music_generator.py     # SunoMusicGenerator class and music generation logic
│   └── routes.py              # Flask route definitions
├── views/                      # Frontend templates and static files
│   ├── README.md              # Documentation for views structure
│   ├── static/
│   │   ├── css/
│   │   │   └── style.css     # Main stylesheet for documentation page
│   │   └── js/
│   │       └── app.js        # JavaScript for interactive API testing
│   └── templates/
│       └── index.html        # HTML template for API documentation
├── migrations/                 # Database migration files (generated by Flask-Migrate)
├── requirements.txt            # Python dependencies
├── .env                        # Environment variables (create from .env.example)
├── .gitignore                  # Git ignore rules
└── README.md                  # This file

Refactoring Changes

1. Configuration Module (conf/)

  • config.py: Contains all configuration settings including:
    • Environment variable loading
    • Logging configuration
    • Flask app initialization
    • Database configuration
    • Cloudinary configuration
    • API keys and URLs

2. Models Module (models/)

  • song.py: Contains database models:
    • SongStatus enum for tracking song generation status
    • Song SQLAlchemy model for storing song metadata

3. Utils Module (utils/)

  • helpers.py: Helper utility functions:

    • sanitize_for_logging(): Text sanitization for logging
    • normalize_content(): Content normalization for LLM responses
    • extract_task_id(): Task ID extraction from API responses
    • upload_to_cloudinary(): Cloudinary upload functionality
    • try_notify(): Notification helper function
  • music_generator.py: Core music generation logic:

    • SunoMusicGenerator class with methods for:
      • Lyrics generation using Google Gemini LLM
      • Music generation using Suno API
      • Status checking
      • Song generation workflow
    • Retry logic and error handling
    • Audio polling functionality
  • routes.py: Flask route definitions:

    • /create_song - Create a new song
    • /check_status/<task_id> - Check song generation status
    • /receive_song - Callback endpoint for Suno API
    • /download - Download generated audio files
    • / - Root endpoint
    • /health - Health check endpoint

4. Main Application (main.py)

  • Simplified entry point that:
    • Imports all necessary modules
    • Registers routes by importing the routes module
    • Initializes the database
    • Starts the Flask application

Benefits of This Refactoring

  1. Separation of Concerns: Each module has a specific responsibility
  2. Maintainability: Code is easier to find, understand, and modify
  3. Reusability: Utility functions can be easily reused across the application
  4. Testability: Individual modules can be tested in isolation
  5. Scalability: New features can be added without cluttering the main file
  6. Configuration Management: All settings are centralized in the config module

No Logic Changes

This refactoring preserves all original functionality while improving code organization. No business logic has been modified - only the structure and organization of the code.

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd coding-interview
  2. Create a virtual environment:

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies:

    pip install -r requirements.txt
  4. Set up environment variables:

    cp .env.example .env
    # Edit .env file with your actual API keys and database credentials
  5. Set up your PostgreSQL database:

    • Create a PostgreSQL database for the application
    • Update the database credentials in your .env file
    • Run the database migrations (see Database Setup section below)

Database Setup

1. Create PostgreSQL Database

First, create the database using your PostgreSQL client:

# Using psql command line
createdb -U admin dhive_ai_music

# Or using psql interactive
psql -U admin -c "CREATE DATABASE dhive_ai_music;"

2. Run Database Migrations

Initialize and run the database migrations:

# Activate virtual environment
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Set Flask app environment variable
export FLASK_APP=main.py

# Initialize migrations (if not already done)
flask db init

# Create migration for current models
flask db migrate -m "Initial migration for Song model"

# Apply migrations to database
flask db upgrade

3. Verify Database Setup

Check that tables were created successfully:

# Connect to database and list tables
psql -U admin -d dhive_ai_music -c "\dt"

You should see a song table in the output.

API Documentation & Testing

The application includes a comprehensive interactive API documentation and testing interface accessible at the root URL.

Features:

  • 📖 Complete API Documentation - All endpoints documented with examples
  • 🧪 Interactive Testing - Test forms for all API endpoints directly in browser
  • 📱 Responsive Design - Works on desktop and mobile devices
  • 🎨 Modern UI - Professional design with real-time status updates
  • Auto-refresh - Automatic status checking for song generation

Accessing the Documentation:

  1. Start the Flask application: python main.py
  2. Visit: http://127.0.0.1:5000
  3. Navigate through the tabs: Overview, API Endpoints, Interactive Testing

Available Endpoints:

  • GET / - API documentation and testing interface
  • GET /health - Health check endpoint
  • POST /create_song - Create a new AI-generated song
  • GET /check_status/<task_id> - Check song generation status
  • POST /download - Download generated audio files

Usage

The application works exactly the same as before. Simply run:

python main.py

Then visit http://127.0.0.1:5000 to access the interactive documentation and test the API endpoints.

Environment Variables

Make sure to set the following environment variables in your .env file:

Database Configuration (PostgreSQL)

  • POSTGRES_USER - Your PostgreSQL username
  • POSTGRES_PASSWORD - Your PostgreSQL password
  • POSTGRES_HOST - PostgreSQL host (usually localhost)
  • POSTGRES_DB - Database name (e.g., dhive_ai_music)

Cloud Storage (Cloudinary)

  • CLOUDINARY_CLOUD_NAME - Your Cloudinary cloud name
  • CLOUDINARY_API_KEY - Your Cloudinary API key
  • CLOUDINARY_API_SECRET - Your Cloudinary API secret

AI Services

  • SUNO_API_KEY - Your Suno API key
  • GEMINI_API_KEY - Your Google Gemini API key

Application

  • APP_BASE_URL - Application base URL (optional, defaults to http://localhost:5000)

Example .env file:

# Database Configuration
POSTGRES_USER=admin
POSTGRES_PASSWORD=your_password
POSTGRES_HOST=localhost
POSTGRES_DB=dhive_ai_music

# Cloudinary Configuration
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

# API Keys
SUNO_API_KEY=your_suno_key
GEMINI_API_KEY=your_gemini_key

# Application Configuration
APP_BASE_URL=http://localhost:5000

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors