m4k1-dev commited on
Commit
f3c9832
·
unverified ·
2 Parent(s): 3c5e053 e6f172e

Merge pull request #1 from synapsec-ai/release/1.0.0

Browse files
Files changed (7) hide show
  1. Dockerfile +26 -0
  2. README.md +36 -2
  3. app/__init__.py +1 -0
  4. app/app.py +158 -0
  5. app/run.py +8 -0
  6. docker-compose.yml +12 -0
  7. pyproject.toml +32 -0
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10.14-bookworm
2
+
3
+ ARG USER_UID=10002
4
+ ARG USER_GID=$USER_UID
5
+ ARG USERNAME=modelapi
6
+
7
+ RUN groupadd --gid $USER_GID $USERNAME \
8
+ && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME
9
+
10
+ # Copy required files
11
+ RUN mkdir -p /modelapi && mkdir -p /home/$USERNAME/.modelapi
12
+ COPY app /modelapi/app
13
+ COPY pyproject.toml /modelapi/pyproject.toml
14
+
15
+ # Setup permissions
16
+ RUN chown -R $USER_UID:$USER_GID /modelapi \
17
+ && chown -R $USER_UID:$USER_GID /home/$USERNAME/.modelapi \
18
+ && chown -R $USER_UID:$USER_GID /home/$USERNAME \
19
+ && chmod -R 755 /home/$USERNAME \
20
+ && chmod -R 755 /modelapi \
21
+ && chmod -R 777 /home/$USERNAME/.modelapi
22
+
23
+ # Change to the user and do subnet installation
24
+ USER $USERNAME
25
+
26
+ RUN /bin/bash -c "python3 -m venv /modelapi/.venv && source /modelapi/.venv/bin/activate && pip3 install -e /modelapi/."
README.md CHANGED
@@ -1,2 +1,36 @@
1
- # SoundsRightModelContainer
2
- Model container template for the SoundsRight subnet.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Container Template for SoundsRight Subnet Miners
2
+
3
+ Miners in [Bittensor's](https://bittensor.com/) [SoundsRight Subnet](https://github.com/synapsec-ai/SoundsRightSubnet) must containerize their models before uploading to HuggingFace. This repo serves as a template.
4
+
5
+ The branches `DENOISING_16000HZ` and `DEREVERBERATION_16000HZ` contain this template fitted with [SGMSE+](https://huggingface.co/sp-uhh/speech-enhancement-sgmse) and are also helpful resources for how to incorporate your model.
6
+
7
+ The `main` branch contains a template for a container that will spin up an API to communicate with the validator. The following entrypoints cannot be altered:
8
+
9
+ 1. `/status/` : Communicates API status
10
+ 2. `/prepare/` : Makes necessary preparations (downloading checkpoints, etc.) and initializes model
11
+ 3. `/upload-audio/` : Upload audio files, save to noisy audio directory
12
+ 4. `/enhance/` : Initialize model, enhance audio files, save to enhanced audio directory
13
+ 5. `/download-enhanced/` : Download enhanced audio files
14
+
15
+ To add your own model to this template, there are a few things that a miner must do:
16
+
17
+ 1. Add the model files under the `model` directory.
18
+ 2. Modify the `modelapi.prepare` method in `app/app.py` with necessary preparations to initialize your model.
19
+ 3. Modify the `modelapi.enhance` method in `app/app.py` with the logic your model uses to enhance audio.
20
+ 4. Update `dependencies` in `pyproject.toml` with the dependencies used by your model.
21
+ 5. If you have directories other than `app` in your repository, be sure to modify the `Dockerfile` accordingly (reference line 12 in the `Dockerfile` for how to do this).
22
+ 6. Cite your sources (if applicable).
23
+
24
+ For your model to be processed by validators, there are a few formatting requirements. Note that the template already has been formatted to fit these guidelines.
25
+
26
+ 1. API endpoints must as outlined above.
27
+ 2. Port must be 6500.
28
+ 3. There should only be one service in `docker-compose.yml`.
29
+ 4. Container must be configured to run as non-root user.
30
+ 5. Container names cannot be any of the following:
31
+
32
+ - common-validator
33
+ - soundsright-validator-debug-mode
34
+ - soundsright-validator-debug-mode-dev
35
+ - soundsright-validator
36
+ - soundsright-validator-dev
app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .app import ModelAPI
app/app.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fastapi
2
+ import shutil
3
+ import os
4
+ import zipfile
5
+ import io
6
+ import uvicorn
7
+ import glob
8
+ from typing import List
9
+
10
+ class ModelAPI:
11
+
12
+ def __init__(self, host, port):
13
+
14
+ self.host = host
15
+ self.port = port
16
+
17
+ self.base_path = os.path.join(os.path.expanduser("~"), ".modelapi")
18
+ self.noisy_audio_path = os.path.join(self.base_path, "noisy_audio")
19
+ self.enhanced_audio_path = os.path.join(self.base_path, "enhanced_audio")
20
+
21
+ # Create directories if they do not exist
22
+ for audio_path in [self.noisy_audio_path, self.enhanced_audio_path]:
23
+ if not os.path.exists(audio_path):
24
+ os.makedirs(audio_path)
25
+
26
+ # Loop through all the files and subdirectories in the directory
27
+ for filename in os.listdir(audio_path):
28
+ file_path = os.path.join(audio_path, filename)
29
+
30
+ # Check if it's a file or directory and remove accordingly
31
+ try:
32
+ if os.path.isfile(file_path) or os.path.islink(file_path):
33
+ os.unlink(file_path) # Remove the file or link
34
+ elif os.path.isdir(file_path):
35
+ shutil.rmtree(file_path) # Remove the directory and its contents
36
+ except Exception as e:
37
+ raise e
38
+
39
+ self.app = fastapi.FastAPI()
40
+ self._setup_routes()
41
+
42
+ def _prepare(self):
43
+ """Miners should modify this function to fit their fine-tuned models.
44
+
45
+ This function will make any preparations necessary to initialize the
46
+ speech enhancement model (i.e. downloading checkpoint files, etc.)
47
+ """
48
+ # Continue from here
49
+ pass
50
+
51
+ def _enhance(self):
52
+ """
53
+ Miners should modify this function to fit their fine-tuned models.
54
+
55
+ This function will:
56
+ 1. Open each noisy .wav file
57
+ 2. Enhance the audio with the model
58
+ 3. Save the enhanced audio in .wav format to MinerAPI.enhanced_audio_path
59
+ """
60
+
61
+ # Define file paths for all noisy files to be enhanced
62
+ noisy_files = sorted(glob.glob(os.path.join(self.noisy_audio_path, '*.wav')))
63
+ for noisy_file in noisy_files:
64
+ # Continue from here
65
+ pass
66
+
67
+ def _setup_routes(self):
68
+ """
69
+ Setup API routes:
70
+
71
+ /status/ : Communicates API status
72
+ /upload-audio/ : Upload audio files, save to noisy audio directory
73
+ /enhance/ : Enhance audio files, save to enhanced audio directory
74
+ /download-enhanced/ : Download enhanced audio files
75
+ """
76
+ self.app.get("/status/")(self.get_status)
77
+ self.app.post("/prepare/")(self.prepare)
78
+ self.app.post("/upload-audio/")(self.upload_audio)
79
+ self.app.post("/enhance/")(self.enhance_audio)
80
+ self.app.get("/download-enhanced/")(self.download_enhanced)
81
+
82
+ def get_status(self):
83
+ try:
84
+ return {"container_running": True}
85
+ except:
86
+ raise fastapi.HTTPException(status_code=500, detail="An error occurred while fetching API status.")
87
+
88
+ def prepare(self):
89
+ try:
90
+ self._prepare()
91
+ return {'preparations': True}
92
+ except:
93
+ return fastapi.HTTPException(status_code=500, detail="An error occurred while fetching API status.")
94
+
95
+ def upload_audio(self, files: List[fastapi.UploadFile] = fastapi.File(...)):
96
+
97
+ uploaded_files = []
98
+
99
+ for file in files:
100
+ try:
101
+ # Define the path to save the file
102
+ file_path = os.path.join(self.noisy_audio_path, file.filename)
103
+
104
+ # Save the uploaded file
105
+ with open(file_path, "wb") as f:
106
+ while contents := file.file.read(1024*1024):
107
+ f.write(contents)
108
+
109
+ # Append the file name to the list of uploaded files
110
+ uploaded_files.append(file.filename)
111
+
112
+ except:
113
+ raise fastapi.HTTPException(status_code=500, detail="An error occurred while uploading the noisy files.")
114
+ finally:
115
+ file.file.close()
116
+
117
+ return {"uploaded_files": uploaded_files, "status": True}
118
+
119
+ def enhance_audio(self):
120
+ try:
121
+ # Enhance audio
122
+ self._enhance()
123
+ # Obtain list of file paths for enhanced audio
124
+ wav_files = glob.glob(os.path.join(self.enhanced_audio_path, '*.wav'))
125
+ # Extract just the file names
126
+ enhanced_files = [os.path.basename(file) for file in wav_files]
127
+ return {"status": True}
128
+
129
+ except Exception as e:
130
+ raise fastapi.HTTPException(status_code=500, detail="An error occurred while enhancing the noisy files.")
131
+
132
+ def download_enhanced(self):
133
+ try:
134
+ # Create an in-memory zip file to hold all the enhanced audio files
135
+ zip_buffer = io.BytesIO()
136
+
137
+ with zipfile.ZipFile(zip_buffer, "w") as zip_file:
138
+ # Add each .wav file in the enhanced_audio_path directory to the zip file
139
+ for wav_file in glob.glob(os.path.join(self.enhanced_audio_path, '*.wav')):
140
+ zip_file.write(wav_file, arcname=os.path.basename(wav_file))
141
+
142
+ # Make sure to seek back to the start of the BytesIO object before sending it
143
+ zip_buffer.seek(0)
144
+
145
+ # Send the zip file to the client as a downloadable file
146
+ return fastapi.responses.StreamingResponse(
147
+ iter([zip_buffer.getvalue()]), # Stream the in-memory content
148
+ media_type="application/zip",
149
+ headers={"Content-Disposition": "attachment; filename=enhanced_audio_files.zip"}
150
+ )
151
+
152
+ except Exception as e:
153
+ # Log the error if needed, and raise an HTTPException to inform the client
154
+ raise fastapi.HTTPException(status_code=500, detail=f"An error occurred while creating the download file: {str(e)}")
155
+
156
+ def run(self):
157
+
158
+ uvicorn.run(self.app, host=self.host, port=self.port)
app/run.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from app import ModelAPI
2
+
3
+ api = ModelAPI(
4
+ host = "0.0.0.0",
5
+ port = 6500
6
+ )
7
+
8
+ api.run()
docker-compose.yml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ modelapi:
3
+ build:
4
+ context: .
5
+ container_name: modelapi
6
+ ports:
7
+ - "6500:6500"
8
+ environment:
9
+ USER_UID: 10002
10
+ USER_GID: 10002
11
+ USERNAME: modelapi
12
+ command: /bin/bash -c "source /modelapi/.venv/bin/activate && python3 /modelapi/app/run.py"
pyproject.toml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "modelapi"
7
+ version = "1.0.0"
8
+ description = "This project implements a container for a fine-tuned audio enhancement model."
9
+ readme = { file = "README.md", content-type = "text/markdown" }
10
+ license = { file = "LICENSE" }
11
+ classifiers = [
12
+ "Development Status :: 3 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Topic :: Software Development :: Build Tools",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Topic :: Scientific/Engineering",
19
+ "Topic :: Scientific/Engineering :: Mathematics",
20
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
21
+ "Topic :: Software Development",
22
+ "Topic :: Software Development :: Libraries",
23
+ "Topic :: Software Development :: Libraries :: Python Modules"
24
+ ]
25
+ requires-python = ">=3.10,<3.12"
26
+
27
+ dependencies = [
28
+ "fastapi==0.115.5", "uvicorn==0.32.0", "python-multipart==0.0.17"
29
+ ]
30
+
31
+ [tool.setuptools.packages.find]
32
+ include = ["app","model"]