Curinha commited on
Commit
7814ee2
1 Parent(s): 05b36f9

Add initial project structure with FastAPI and audio generation functionality

Browse files
Files changed (5) hide show
  1. .gitignore +171 -0
  2. Dockerfile +42 -0
  3. app.py +89 -0
  4. requirements.txt +10 -0
  5. sound_generator.py +51 -0
.gitignore ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.8
2
+
3
+ # Set a writable cache directory for Hugging Face models
4
+ ENV HF_HOME="/tmp/huggingface_cache"
5
+ ENV MPLCONFIGDIR="/tmp/matplotlib_cache"
6
+ ENV TRANSFORMERS_CACHE="/tmp/huggingface"
7
+ ENV NUMBA_CACHE_DIR="/tmp/numba_cache"
8
+
9
+ # Create and set correct permissions for cache directories
10
+ RUN mkdir -p $HF_HOME $MPLCONFIGDIR $TRANSFORMERS_CACHE $NUMBA_CACHE_DIR \
11
+ && chmod -R 777 $HF_HOME $MPLCONFIGDIR $TRANSFORMERS_CACHE $NUMBA_CACHE_DIR
12
+
13
+ # Install system dependencies
14
+ RUN apt-get update && apt-get install -y \
15
+ ffmpeg \
16
+ && rm -rf /var/lib/apt/lists/*
17
+
18
+ # Set up a non-root user to avoid permission issues
19
+ RUN useradd -m appuser
20
+ USER appuser
21
+
22
+ # Set the PATH to include local bin directory
23
+ ENV PATH="/home/appuser/.local/bin:$PATH"
24
+
25
+ # Install Python dependencies
26
+ COPY --chown=appuser:appuser requirements.txt .
27
+ RUN pip install --no-cache-dir -r requirements.txt
28
+
29
+ # Manually install uvicorn in case it failed above
30
+ RUN pip install uvicorn
31
+
32
+ # Verify that uvicorn was installed
33
+ RUN pip show uvicorn
34
+
35
+ # Copy the API code
36
+ COPY --chown=appuser:appuser . .
37
+
38
+ # Expose the port
39
+ EXPOSE 5000
40
+
41
+ # Run the application
42
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "5000"]
app.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import uvicorn
4
+
5
+ from sound_generator import generate_sound, generate_music
6
+ from fastapi import FastAPI, HTTPException
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.responses import FileResponse
9
+ from pydantic import BaseModel
10
+
11
+ # Create the FastAPI app
12
+ app = FastAPI()
13
+
14
+
15
+ # Configuraci贸n de CORS para permitir solicitudes desde cualquier origen
16
+ app.add_middleware(
17
+ CORSMiddleware,
18
+ allow_origins=[
19
+ "*"
20
+ ], # Permitir todos los or铆genes (puedes restringirlo a tus or铆genes espec铆ficos)
21
+ allow_credentials=True,
22
+ allow_methods=["*"], # Permitir todos los m茅todos HTTP (GET, POST, OPTIONS, etc.)
23
+ allow_headers=["*"], # Permitir todos los encabezados
24
+ )
25
+
26
+
27
+ # Define a Pydantic model to handle the input prompt
28
+ class AudioRequest(BaseModel):
29
+ prompt: str
30
+
31
+
32
+ @app.post("/generate-sound/")
33
+ async def generate_sound_endpoint(request: AudioRequest):
34
+ try:
35
+ # Llamada a la funci贸n para generar el sonido
36
+ audio_file_path = generate_sound(request.prompt)
37
+
38
+ # Verifica si el archivo se ha generado correctamente
39
+ if not os.path.exists(audio_file_path):
40
+ raise HTTPException(
41
+ status_code=404, detail="Archivo de audio no encontrado."
42
+ )
43
+
44
+ # Regresar el archivo generado como una respuesta de descarga
45
+ return FileResponse(
46
+ audio_file_path, media_type="audio/wav", filename="generated_audio.wav"
47
+ )
48
+
49
+ except Exception as e:
50
+ raise HTTPException(status_code=500, detail=str(e))
51
+
52
+
53
+ @app.post("/generate-music/")
54
+ async def generate_music_endpoint(request: AudioRequest):
55
+ try:
56
+ # Call the synchronous generate_music function
57
+ audio_file_path = generate_music(request.prompt)
58
+
59
+ # Verifies if the file has been generated correctly
60
+ if not os.path.exists(audio_file_path):
61
+ raise HTTPException(
62
+ status_code=404, detail="Archivo de audio no encontrado."
63
+ )
64
+
65
+ # Return the generated file as a download response
66
+ return FileResponse(
67
+ audio_file_path, media_type="audio/wav", filename="generated_audio.wav"
68
+ )
69
+
70
+ except Exception as e:
71
+ raise HTTPException(status_code=500, detail=str(e))
72
+
73
+
74
+ # Crear interfaz de Gradio separadamente
75
+ with gr.Blocks() as demo:
76
+ gr.Markdown("# API de Sonidos Generativos")
77
+ gr.Markdown("Bienvenido al servicio de generaci贸n de sonidos mediante IA.")
78
+ gr.Markdown(
79
+ "Esta API est谩 disponible para uso a trav茅s de los siguientes endpoints:"
80
+ )
81
+ gr.Markdown("- Generar sonido: `/generate-sound/`")
82
+ gr.Markdown("- Generar m煤sica: `/generate-music/`")
83
+ gr.Markdown("- Documentaci贸n de la API: `/docs`")
84
+
85
+ # Montar Gradio en FastAPI - IMPORTANTE: esto debe hacerse antes de iniciar el servidor
86
+ app = gr.mount_gradio_app(app, demo, path="/")
87
+
88
+ if __name__ == "__main__":
89
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ scipy==1.9.3
2
+ git+https://github.com/facebookresearch/audiocraft.git
3
+ ffmpeg==1.4
4
+ numpy==1.24.4
5
+ spacy==3.7.6
6
+ torch==2.1.0
7
+ pydantic==2.1.1
8
+ fastapi==0.115.11
9
+ uvicorn==0.33.0
10
+ gradio==5.20.1
sound_generator.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from audiocraft.models import AudioGen, MusicGen
2
+ from audiocraft.data.audio import audio_write
3
+
4
+ # Load the pretrained model (you can choose "small", "medium", or "large")
5
+ sound_model = AudioGen.get_pretrained('facebook/audiogen-medium')
6
+ music_model = MusicGen.get_pretrained('facebook/musicgen-small')
7
+
8
+ # Set generation parameters (for example, audio duration of 8 seconds)
9
+ sound_model.set_generation_params(duration=5)
10
+ music_model.set_generation_params(duration=5)
11
+
12
+ def generate_sound(prompt: str):
13
+ """
14
+ Generate sound using Audiocraft based on the given prompt.
15
+
16
+ Args:
17
+ - prompt (str): The description of the sound/music to generate.
18
+
19
+ Returns:
20
+ - str: The path to the saved audio file.
21
+ """
22
+ # Generate the audio for the provided prompt
23
+ descriptions = [prompt] # We use the prompt as a description for the model
24
+ wav = sound_model.generate(descriptions) # Generates 2 samples
25
+
26
+ # Save the generated audio file with loudness normalization
27
+ output_path = 'generated_audio'
28
+ audio_write(output_path, wav[0].cpu(), sound_model.sample_rate, strategy="loudness")
29
+
30
+ return f"{output_path}.wav"
31
+
32
+
33
+ def generate_music(prompt: str):
34
+ """
35
+ Generate music using Audiocraft based on the given prompt.
36
+
37
+ Args:
38
+ - prompt (str): The description of the music to generate.
39
+
40
+ Returns:
41
+ - str: The path to the saved audio file.
42
+ """
43
+ # Generate the music for the provided prompt
44
+ descriptions = [prompt] # We use the prompt as a description for the model
45
+ wav = music_model.generate(descriptions) # Generates 2 samples
46
+
47
+ # Save the generated audio file with loudness normalization
48
+ output_path = 'generated_audio'
49
+ audio_write(output_path, wav[0].cpu(), music_model.sample_rate, strategy="loudness")
50
+
51
+ return f"{output_path}.wav"