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
| 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)
|