update
Browse files- .gitattributes +1 -0
- .gitignore +14 -0
- Dockerfile +24 -0
- examples/wav2vec2/test_audeering.py +106 -0
- log.py +229 -0
- main.py +183 -0
- project_settings.py +22 -0
- requirements.txt +7 -0
- toolbox/__init__.py +6 -0
- toolbox/age_and_gender/__init__.py +6 -0
- toolbox/age_and_gender/models/__init__.py +6 -0
- toolbox/age_and_gender/models/audeering.py +103 -0
- toolbox/json/__init__.py +6 -0
- toolbox/json/misc.py +63 -0
- toolbox/os/__init__.py +6 -0
- toolbox/os/command.py +59 -0
- toolbox/os/environment.py +114 -0
- toolbox/os/other.py +9 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
.git/
|
| 3 |
+
.idea/
|
| 4 |
+
|
| 5 |
+
/data/
|
| 6 |
+
/dotenv/
|
| 7 |
+
/logs/
|
| 8 |
+
/pretrained_models
|
| 9 |
+
/trained_models
|
| 10 |
+
/temp/
|
| 11 |
+
|
| 12 |
+
**/__pycache__/
|
| 13 |
+
|
| 14 |
+
**/*.wav
|
Dockerfile
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /code
|
| 4 |
+
|
| 5 |
+
COPY . /code
|
| 6 |
+
|
| 7 |
+
RUN apt-get update
|
| 8 |
+
RUN apt-get install -y ffmpeg build-essential
|
| 9 |
+
|
| 10 |
+
RUN pip install --upgrade pip
|
| 11 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
| 12 |
+
|
| 13 |
+
RUN useradd -m -u 1000 user
|
| 14 |
+
|
| 15 |
+
USER user
|
| 16 |
+
|
| 17 |
+
ENV HOME=/home/user \
|
| 18 |
+
PATH=/home/user/.local/bin:$PATH
|
| 19 |
+
|
| 20 |
+
WORKDIR $HOME/app
|
| 21 |
+
|
| 22 |
+
COPY --chown=user . $HOME/app
|
| 23 |
+
|
| 24 |
+
CMD ["python3", "main.py"]
|
examples/wav2vec2/test_audeering.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
https://arxiv.org/abs/2306.16962
|
| 5 |
+
|
| 6 |
+
https://huggingface.co/audeering/wav2vec2-large-robust-24-ft-age-gender
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import librosa
|
| 13 |
+
from transformers import Wav2Vec2Processor
|
| 14 |
+
from transformers.models.wav2vec2.modeling_wav2vec2 import Wav2Vec2Model, Wav2Vec2PreTrainedModel
|
| 15 |
+
|
| 16 |
+
from project_settings import project_path
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_args():
|
| 20 |
+
parser = argparse.ArgumentParser()
|
| 21 |
+
parser.add_argument(
|
| 22 |
+
"--model_path",
|
| 23 |
+
# default=(project_path / "pretrained_models/wav2vec2-large-robust-6-ft-age-gender").as_posix(),
|
| 24 |
+
default=(project_path / "pretrained_models/wav2vec2-large-robust-6-ft-age-gender").as_posix(),
|
| 25 |
+
type=str,
|
| 26 |
+
)
|
| 27 |
+
parser.add_argument(
|
| 28 |
+
"--speech_file",
|
| 29 |
+
# default=(project_path / "data/examples/voicemail-female-1.wav").as_posix(),
|
| 30 |
+
# default=(project_path / "data/examples/voicemail-female-2.wav").as_posix(),
|
| 31 |
+
# default=(project_path / "data/examples/voicemail-female-3.wav").as_posix(),
|
| 32 |
+
# default=(project_path / "data/examples/voicemail-male-1.wav").as_posix(),
|
| 33 |
+
# default=(project_path / "data/examples/voicemail-male-2.wav").as_posix(),
|
| 34 |
+
default=(project_path / "data/examples/speech-male-1.wav").as_posix(),
|
| 35 |
+
type=str,
|
| 36 |
+
)
|
| 37 |
+
args = parser.parse_args()
|
| 38 |
+
return args
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ModelHead(nn.Module):
|
| 42 |
+
def __init__(self, config, num_labels):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 45 |
+
self.dropout = nn.Dropout(config.final_dropout)
|
| 46 |
+
self.out_proj = nn.Linear(config.hidden_size, num_labels)
|
| 47 |
+
|
| 48 |
+
def forward(self, features, **kwargs):
|
| 49 |
+
x = features
|
| 50 |
+
x = self.dropout(x)
|
| 51 |
+
x = self.dense(x)
|
| 52 |
+
x = torch.tanh(x)
|
| 53 |
+
x = self.dropout(x)
|
| 54 |
+
x = self.out_proj(x)
|
| 55 |
+
return x
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class AgeGenderModel(Wav2Vec2PreTrainedModel):
|
| 59 |
+
def __init__(self, config):
|
| 60 |
+
super().__init__(config)
|
| 61 |
+
self.config = config
|
| 62 |
+
self.wav2vec2 = Wav2Vec2Model(config)
|
| 63 |
+
self.age = ModelHead(config, 1)
|
| 64 |
+
self.gender = ModelHead(config, 3)
|
| 65 |
+
self.init_weights()
|
| 66 |
+
|
| 67 |
+
def forward(self,
|
| 68 |
+
input_values,
|
| 69 |
+
):
|
| 70 |
+
outputs = self.wav2vec2(input_values)
|
| 71 |
+
hidden_states = outputs[0]
|
| 72 |
+
hidden_states = torch.mean(hidden_states, dim=1)
|
| 73 |
+
|
| 74 |
+
logits_age = self.age.forward(hidden_states)
|
| 75 |
+
logits_gender = torch.softmax(self.gender.forward(hidden_states), dim=1)
|
| 76 |
+
|
| 77 |
+
return hidden_states, logits_age, logits_gender
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main():
|
| 81 |
+
args = get_args()
|
| 82 |
+
|
| 83 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 84 |
+
|
| 85 |
+
processor: Wav2Vec2Processor = Wav2Vec2Processor.from_pretrained(args.model_path)
|
| 86 |
+
model = AgeGenderModel.from_pretrained(args.model_path)
|
| 87 |
+
model.eval()
|
| 88 |
+
|
| 89 |
+
# signal
|
| 90 |
+
signal, sample_rate = librosa.load(args.speech_file, sr=16000)
|
| 91 |
+
|
| 92 |
+
y = processor.__call__(signal, sampling_rate=sample_rate)
|
| 93 |
+
y = y['input_values'][0]
|
| 94 |
+
y = y.reshape(1, -1)
|
| 95 |
+
y = torch.from_numpy(y).to(device)
|
| 96 |
+
|
| 97 |
+
_, age, gender = model.forward(y)
|
| 98 |
+
print(f"age: {age}")
|
| 99 |
+
# female male child
|
| 100 |
+
print(f"gender: {gender}")
|
| 101 |
+
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == '__main__':
|
| 106 |
+
main()
|
log.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import logging
|
| 4 |
+
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def setup_size_rotating(log_directory: str):
|
| 9 |
+
fmt = "%(asctime)s - %(name)s - %(levelname)s %(filename)s:%(lineno)d > %(message)s"
|
| 10 |
+
|
| 11 |
+
stream_handler = logging.StreamHandler()
|
| 12 |
+
stream_handler.setLevel(logging.INFO)
|
| 13 |
+
stream_handler.setFormatter(logging.Formatter(fmt))
|
| 14 |
+
|
| 15 |
+
# main
|
| 16 |
+
main_logger = logging.getLogger("main")
|
| 17 |
+
main_logger.addHandler(stream_handler)
|
| 18 |
+
main_info_file_handler = RotatingFileHandler(
|
| 19 |
+
filename=os.path.join(log_directory, "main.log"),
|
| 20 |
+
maxBytes=100*1024*1024, # 100MB
|
| 21 |
+
encoding="utf-8",
|
| 22 |
+
backupCount=2,
|
| 23 |
+
)
|
| 24 |
+
main_info_file_handler.setLevel(logging.INFO)
|
| 25 |
+
main_info_file_handler.setFormatter(logging.Formatter(fmt))
|
| 26 |
+
main_logger.addHandler(main_info_file_handler)
|
| 27 |
+
|
| 28 |
+
# http
|
| 29 |
+
http_logger = logging.getLogger("http")
|
| 30 |
+
http_file_handler = RotatingFileHandler(
|
| 31 |
+
filename=os.path.join(log_directory, "http.log"),
|
| 32 |
+
maxBytes=100*1024*1024, # 100MB
|
| 33 |
+
encoding="utf-8",
|
| 34 |
+
backupCount=2,
|
| 35 |
+
)
|
| 36 |
+
http_file_handler.setLevel(logging.DEBUG)
|
| 37 |
+
http_file_handler.setFormatter(logging.Formatter(fmt))
|
| 38 |
+
http_logger.addHandler(http_file_handler)
|
| 39 |
+
|
| 40 |
+
# api
|
| 41 |
+
api_logger = logging.getLogger("api")
|
| 42 |
+
api_file_handler = RotatingFileHandler(
|
| 43 |
+
filename=os.path.join(log_directory, "api.log"),
|
| 44 |
+
maxBytes=10*1024*1024, # 10MB
|
| 45 |
+
encoding="utf-8",
|
| 46 |
+
backupCount=2,
|
| 47 |
+
)
|
| 48 |
+
api_file_handler.setLevel(logging.DEBUG)
|
| 49 |
+
api_file_handler.setFormatter(logging.Formatter(fmt))
|
| 50 |
+
api_logger.addHandler(api_file_handler)
|
| 51 |
+
|
| 52 |
+
# toolbox
|
| 53 |
+
toolbox_logger = logging.getLogger("toolbox")
|
| 54 |
+
toolbox_logger.addHandler(stream_handler)
|
| 55 |
+
toolbox_file_handler = RotatingFileHandler(
|
| 56 |
+
filename=os.path.join(log_directory, "toolbox.log"),
|
| 57 |
+
maxBytes=10*1024*1024, # 10MB
|
| 58 |
+
encoding="utf-8",
|
| 59 |
+
backupCount=2,
|
| 60 |
+
)
|
| 61 |
+
toolbox_file_handler.setLevel(logging.DEBUG)
|
| 62 |
+
toolbox_file_handler.setFormatter(logging.Formatter(fmt))
|
| 63 |
+
toolbox_logger.addHandler(toolbox_file_handler)
|
| 64 |
+
|
| 65 |
+
# alarm
|
| 66 |
+
alarm_logger = logging.getLogger("alarm")
|
| 67 |
+
alarm_file_handler = RotatingFileHandler(
|
| 68 |
+
filename=os.path.join(log_directory, "alarm.log"),
|
| 69 |
+
maxBytes=1*1024*1024, # 1MB
|
| 70 |
+
encoding="utf-8",
|
| 71 |
+
backupCount=2,
|
| 72 |
+
)
|
| 73 |
+
alarm_file_handler.setLevel(logging.DEBUG)
|
| 74 |
+
alarm_file_handler.setFormatter(logging.Formatter(fmt))
|
| 75 |
+
alarm_logger.addHandler(alarm_file_handler)
|
| 76 |
+
|
| 77 |
+
debug_file_handler = RotatingFileHandler(
|
| 78 |
+
filename=os.path.join(log_directory, "debug.log"),
|
| 79 |
+
maxBytes=1*1024*1024, # 1MB
|
| 80 |
+
encoding="utf-8",
|
| 81 |
+
backupCount=2,
|
| 82 |
+
)
|
| 83 |
+
debug_file_handler.setLevel(logging.DEBUG)
|
| 84 |
+
debug_file_handler.setFormatter(logging.Formatter(fmt))
|
| 85 |
+
|
| 86 |
+
info_file_handler = RotatingFileHandler(
|
| 87 |
+
filename=os.path.join(log_directory, "info.log"),
|
| 88 |
+
maxBytes=1*1024*1024, # 1MB
|
| 89 |
+
encoding="utf-8",
|
| 90 |
+
backupCount=2,
|
| 91 |
+
)
|
| 92 |
+
info_file_handler.setLevel(logging.INFO)
|
| 93 |
+
info_file_handler.setFormatter(logging.Formatter(fmt))
|
| 94 |
+
|
| 95 |
+
error_file_handler = RotatingFileHandler(
|
| 96 |
+
filename=os.path.join(log_directory, "error.log"),
|
| 97 |
+
maxBytes=1*1024*1024, # 1MB
|
| 98 |
+
encoding="utf-8",
|
| 99 |
+
backupCount=2,
|
| 100 |
+
)
|
| 101 |
+
error_file_handler.setLevel(logging.ERROR)
|
| 102 |
+
error_file_handler.setFormatter(logging.Formatter(fmt))
|
| 103 |
+
|
| 104 |
+
logging.basicConfig(
|
| 105 |
+
level=logging.DEBUG,
|
| 106 |
+
datefmt="%a, %d %b %Y %H:%M:%S",
|
| 107 |
+
handlers=[
|
| 108 |
+
debug_file_handler,
|
| 109 |
+
info_file_handler,
|
| 110 |
+
error_file_handler,
|
| 111 |
+
]
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def setup_time_rotating(log_directory: str):
|
| 116 |
+
fmt = "%(asctime)s - %(name)s - %(levelname)s %(filename)s:%(lineno)d > %(message)s"
|
| 117 |
+
|
| 118 |
+
stream_handler = logging.StreamHandler()
|
| 119 |
+
stream_handler.setLevel(logging.INFO)
|
| 120 |
+
stream_handler.setFormatter(logging.Formatter(fmt))
|
| 121 |
+
|
| 122 |
+
# main
|
| 123 |
+
main_logger = logging.getLogger("main")
|
| 124 |
+
main_logger.addHandler(stream_handler)
|
| 125 |
+
main_info_file_handler = TimedRotatingFileHandler(
|
| 126 |
+
filename=os.path.join(log_directory, "main.log"),
|
| 127 |
+
encoding="utf-8",
|
| 128 |
+
when="midnight",
|
| 129 |
+
interval=1,
|
| 130 |
+
backupCount=7
|
| 131 |
+
)
|
| 132 |
+
main_info_file_handler.setLevel(logging.INFO)
|
| 133 |
+
main_info_file_handler.setFormatter(logging.Formatter(fmt))
|
| 134 |
+
main_logger.addHandler(main_info_file_handler)
|
| 135 |
+
|
| 136 |
+
# http
|
| 137 |
+
http_logger = logging.getLogger("http")
|
| 138 |
+
http_file_handler = TimedRotatingFileHandler(
|
| 139 |
+
filename=os.path.join(log_directory, "http.log"),
|
| 140 |
+
encoding='utf-8',
|
| 141 |
+
when="midnight",
|
| 142 |
+
interval=1,
|
| 143 |
+
backupCount=7
|
| 144 |
+
)
|
| 145 |
+
http_file_handler.setLevel(logging.DEBUG)
|
| 146 |
+
http_file_handler.setFormatter(logging.Formatter(fmt))
|
| 147 |
+
http_logger.addHandler(http_file_handler)
|
| 148 |
+
|
| 149 |
+
# api
|
| 150 |
+
api_logger = logging.getLogger("api")
|
| 151 |
+
api_file_handler = TimedRotatingFileHandler(
|
| 152 |
+
filename=os.path.join(log_directory, "api.log"),
|
| 153 |
+
encoding='utf-8',
|
| 154 |
+
when="midnight",
|
| 155 |
+
interval=1,
|
| 156 |
+
backupCount=7
|
| 157 |
+
)
|
| 158 |
+
api_file_handler.setLevel(logging.DEBUG)
|
| 159 |
+
api_file_handler.setFormatter(logging.Formatter(fmt))
|
| 160 |
+
api_logger.addHandler(api_file_handler)
|
| 161 |
+
|
| 162 |
+
# toolbox
|
| 163 |
+
toolbox_logger = logging.getLogger("toolbox")
|
| 164 |
+
toolbox_file_handler = RotatingFileHandler(
|
| 165 |
+
filename=os.path.join(log_directory, "toolbox.log"),
|
| 166 |
+
maxBytes=10*1024*1024, # 10MB
|
| 167 |
+
encoding="utf-8",
|
| 168 |
+
backupCount=2,
|
| 169 |
+
)
|
| 170 |
+
toolbox_file_handler.setLevel(logging.DEBUG)
|
| 171 |
+
toolbox_file_handler.setFormatter(logging.Formatter(fmt))
|
| 172 |
+
toolbox_logger.addHandler(toolbox_file_handler)
|
| 173 |
+
|
| 174 |
+
# alarm
|
| 175 |
+
alarm_logger = logging.getLogger("alarm")
|
| 176 |
+
alarm_file_handler = TimedRotatingFileHandler(
|
| 177 |
+
filename=os.path.join(log_directory, "alarm.log"),
|
| 178 |
+
encoding="utf-8",
|
| 179 |
+
when="midnight",
|
| 180 |
+
interval=1,
|
| 181 |
+
backupCount=7
|
| 182 |
+
)
|
| 183 |
+
alarm_file_handler.setLevel(logging.DEBUG)
|
| 184 |
+
alarm_file_handler.setFormatter(logging.Formatter(fmt))
|
| 185 |
+
alarm_logger.addHandler(alarm_file_handler)
|
| 186 |
+
|
| 187 |
+
debug_file_handler = TimedRotatingFileHandler(
|
| 188 |
+
filename=os.path.join(log_directory, "debug.log"),
|
| 189 |
+
encoding="utf-8",
|
| 190 |
+
when="D",
|
| 191 |
+
interval=1,
|
| 192 |
+
backupCount=7
|
| 193 |
+
)
|
| 194 |
+
debug_file_handler.setLevel(logging.DEBUG)
|
| 195 |
+
debug_file_handler.setFormatter(logging.Formatter(fmt))
|
| 196 |
+
|
| 197 |
+
info_file_handler = TimedRotatingFileHandler(
|
| 198 |
+
filename=os.path.join(log_directory, "info.log"),
|
| 199 |
+
encoding="utf-8",
|
| 200 |
+
when="D",
|
| 201 |
+
interval=1,
|
| 202 |
+
backupCount=7
|
| 203 |
+
)
|
| 204 |
+
info_file_handler.setLevel(logging.INFO)
|
| 205 |
+
info_file_handler.setFormatter(logging.Formatter(fmt))
|
| 206 |
+
|
| 207 |
+
error_file_handler = TimedRotatingFileHandler(
|
| 208 |
+
filename=os.path.join(log_directory, "error.log"),
|
| 209 |
+
encoding="utf-8",
|
| 210 |
+
when="D",
|
| 211 |
+
interval=1,
|
| 212 |
+
backupCount=7
|
| 213 |
+
)
|
| 214 |
+
error_file_handler.setLevel(logging.ERROR)
|
| 215 |
+
error_file_handler.setFormatter(logging.Formatter(fmt))
|
| 216 |
+
|
| 217 |
+
logging.basicConfig(
|
| 218 |
+
level=logging.DEBUG,
|
| 219 |
+
datefmt="%a, %d %b %Y %H:%M:%S",
|
| 220 |
+
handlers=[
|
| 221 |
+
debug_file_handler,
|
| 222 |
+
info_file_handler,
|
| 223 |
+
error_file_handler,
|
| 224 |
+
]
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
pass
|
main.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import argparse
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import platform
|
| 9 |
+
import tempfile
|
| 10 |
+
import time
|
| 11 |
+
import uuid
|
| 12 |
+
|
| 13 |
+
import gradio as gr
|
| 14 |
+
import librosa
|
| 15 |
+
import numpy as np
|
| 16 |
+
from scipy.io import wavfile
|
| 17 |
+
|
| 18 |
+
import log
|
| 19 |
+
from project_settings import environment, project_path, log_directory
|
| 20 |
+
from toolbox.os.command import Command
|
| 21 |
+
from toolbox.age_and_gender.models.audeering import AudeeringModel
|
| 22 |
+
|
| 23 |
+
log.setup_size_rotating(log_directory=log_directory)
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger("main")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def get_args():
|
| 29 |
+
parser = argparse.ArgumentParser()
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
"--examples_dir",
|
| 32 |
+
default=(project_path / "data/examples").as_posix(),
|
| 33 |
+
type=str,
|
| 34 |
+
)
|
| 35 |
+
args = parser.parse_args()
|
| 36 |
+
return args
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def save_input_audio(sample_rate: int, signal: np.ndarray) -> str:
|
| 40 |
+
temp_audio_dir = Path(tempfile.gettempdir()) / "input_audio"
|
| 41 |
+
temp_audio_dir.mkdir(parents=True, exist_ok=True)
|
| 42 |
+
filename = temp_audio_dir / f"{uuid.uuid4()}.wav"
|
| 43 |
+
filename = filename.as_posix()
|
| 44 |
+
wavfile.write(
|
| 45 |
+
filename,
|
| 46 |
+
sample_rate, signal
|
| 47 |
+
)
|
| 48 |
+
return filename
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def shell(cmd: str):
|
| 52 |
+
return Command.popen(cmd)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
age_and_gender_model_map = {
|
| 56 |
+
"audeering-6-ft":{
|
| 57 |
+
"infer_cls": AudeeringModel,
|
| 58 |
+
"kwargs": {
|
| 59 |
+
"model_path":
|
| 60 |
+
(project_path / "pretrained_models/wav2vec2-large-robust-6-ft-age-gender").as_posix()
|
| 61 |
+
if platform.system() == "Windows" else "audeering/wav2vec2-large-robust-6-ft-age-gender"
|
| 62 |
+
},
|
| 63 |
+
"sample_rate": 16000,
|
| 64 |
+
},
|
| 65 |
+
"audeering-24-ft": {
|
| 66 |
+
"infer_cls": AudeeringModel,
|
| 67 |
+
"kwargs": {
|
| 68 |
+
"model_path":
|
| 69 |
+
(project_path / "pretrained_models/wav2vec2-large-robust-24-ft-age-gender").as_posix()
|
| 70 |
+
if platform.system() == "Windows" else "audeering/wav2vec2-large-robust-24-ft-age-gender",
|
| 71 |
+
},
|
| 72 |
+
"sample_rate": 16000,
|
| 73 |
+
},
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@lru_cache(maxsize=3)
|
| 78 |
+
def load_get_age_and_gender_model(infer_cls, **kwargs):
|
| 79 |
+
infer_engine = infer_cls(**kwargs)
|
| 80 |
+
|
| 81 |
+
return infer_engine
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def when_click_get_age_and_gender_button(audio_t, engine: str):
|
| 85 |
+
sample_rate, signal = audio_t
|
| 86 |
+
filename = save_input_audio(sample_rate, signal)
|
| 87 |
+
|
| 88 |
+
logger.info(f"run get_age_and_gender; engine: {engine}.")
|
| 89 |
+
|
| 90 |
+
infer_engine_param = age_and_gender_model_map.get(engine)
|
| 91 |
+
if infer_engine_param is None:
|
| 92 |
+
raise gr.Error(f"invalid denoise engine: {engine}.")
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
infer_cls = infer_engine_param["infer_cls"]
|
| 96 |
+
kwargs = infer_engine_param["kwargs"]
|
| 97 |
+
sample_rate = infer_engine_param["sample_rate"]
|
| 98 |
+
|
| 99 |
+
signal, _ = librosa.load(filename, sr=sample_rate)
|
| 100 |
+
duration = len(signal) / sample_rate
|
| 101 |
+
|
| 102 |
+
infer_engine = load_get_age_and_gender_model(infer_cls=infer_cls, **kwargs)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
time_begin = time.time()
|
| 106 |
+
age_and_gender = infer_engine.__call__(signal, sample_rate)
|
| 107 |
+
time_cost = time.time() - time_begin
|
| 108 |
+
|
| 109 |
+
rtf = time_cost / duration
|
| 110 |
+
|
| 111 |
+
result = {
|
| 112 |
+
**age_and_gender,
|
| 113 |
+
"duration": round(duration, 4),
|
| 114 |
+
"time_cost": round(time_cost, 4),
|
| 115 |
+
"rtf": round(rtf, 4),
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
result = json.dumps(result, ensure_ascii=False, indent=4)
|
| 119 |
+
except Exception as e:
|
| 120 |
+
raise gr.Error(f"get_age_and_gender failed, error type: {type(e)}, error text: {str(e)}.")
|
| 121 |
+
|
| 122 |
+
return result
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def main():
|
| 126 |
+
args = get_args()
|
| 127 |
+
|
| 128 |
+
# examples
|
| 129 |
+
examples_dir = Path(args.examples_dir)
|
| 130 |
+
|
| 131 |
+
# choices
|
| 132 |
+
age_and_gender_model_choices = list(age_and_gender_model_map.keys())
|
| 133 |
+
|
| 134 |
+
# ui
|
| 135 |
+
with gr.Blocks() as blocks:
|
| 136 |
+
with gr.Tabs():
|
| 137 |
+
with gr.TabItem("age_and_gender"):
|
| 138 |
+
with gr.Row():
|
| 139 |
+
with gr.Column(variant="panel", scale=5):
|
| 140 |
+
ag_audio = gr.Audio(label="audio")
|
| 141 |
+
ag_engine = gr.Dropdown(choices=age_and_gender_model_choices, value=age_and_gender_model_choices[0], label="engine")
|
| 142 |
+
ag_button = gr.Button(variant="primary")
|
| 143 |
+
with gr.Column(variant="panel", scale=5):
|
| 144 |
+
ag_output = gr.Text(label="output")
|
| 145 |
+
|
| 146 |
+
gr.Examples(
|
| 147 |
+
examples=[
|
| 148 |
+
[filename.as_posix(), age_and_gender_model_choices[0]]
|
| 149 |
+
for filename in examples_dir.glob("*.wav")
|
| 150 |
+
],
|
| 151 |
+
inputs=[ag_audio, ag_engine],
|
| 152 |
+
outputs=[ag_output],
|
| 153 |
+
fn=when_click_get_age_and_gender_button,
|
| 154 |
+
)
|
| 155 |
+
ag_button.click(
|
| 156 |
+
when_click_get_age_and_gender_button,
|
| 157 |
+
inputs=[ag_audio, ag_engine],
|
| 158 |
+
outputs=[ag_output],
|
| 159 |
+
)
|
| 160 |
+
with gr.TabItem("shell"):
|
| 161 |
+
shell_text = gr.Textbox(label="cmd")
|
| 162 |
+
shell_button = gr.Button("run")
|
| 163 |
+
shell_output = gr.Textbox(label="output")
|
| 164 |
+
|
| 165 |
+
shell_button.click(
|
| 166 |
+
shell,
|
| 167 |
+
inputs=[shell_text,],
|
| 168 |
+
outputs=[shell_output],
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# http://127.0.0.1:7860/
|
| 172 |
+
# http://10.75.27.247:7861/
|
| 173 |
+
blocks.queue().launch(
|
| 174 |
+
share=False if platform.system() == "Windows" else False,
|
| 175 |
+
# server_name="127.0.0.1" if platform.system() == "Windows" else "0.0.0.0",
|
| 176 |
+
server_name="0.0.0.0",
|
| 177 |
+
server_port=environment.get("port", 7860, dtype=int),
|
| 178 |
+
)
|
| 179 |
+
return
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
main()
|
project_settings.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from toolbox.os.environment import EnvironmentManager
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
project_path = os.path.abspath(os.path.dirname(__file__))
|
| 10 |
+
project_path = Path(project_path)
|
| 11 |
+
|
| 12 |
+
log_directory = project_path / "logs"
|
| 13 |
+
log_directory.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
environment = EnvironmentManager(
|
| 16 |
+
path=os.path.join(project_path, "dotenv"),
|
| 17 |
+
env=os.environ.get("environment", "dev"),
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == '__main__':
|
| 22 |
+
pass
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
transformers
|
| 3 |
+
torch
|
| 4 |
+
torchaudio
|
| 5 |
+
numpy
|
| 6 |
+
librosa
|
| 7 |
+
python-dotenv
|
toolbox/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == '__main__':
|
| 6 |
+
pass
|
toolbox/age_and_gender/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == '__main__':
|
| 6 |
+
pass
|
toolbox/age_and_gender/models/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == '__main__':
|
| 6 |
+
pass
|
toolbox/age_and_gender/models/audeering.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import argparse
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import librosa
|
| 9 |
+
from transformers import Wav2Vec2Processor
|
| 10 |
+
from transformers.models.wav2vec2.modeling_wav2vec2 import Wav2Vec2Model, Wav2Vec2PreTrainedModel
|
| 11 |
+
|
| 12 |
+
from project_settings import project_path
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ModelHead(nn.Module):
|
| 16 |
+
def __init__(self, config, num_labels):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 19 |
+
self.dropout = nn.Dropout(config.final_dropout)
|
| 20 |
+
self.out_proj = nn.Linear(config.hidden_size, num_labels)
|
| 21 |
+
|
| 22 |
+
def forward(self, features, **kwargs):
|
| 23 |
+
x = features
|
| 24 |
+
x = self.dropout(x)
|
| 25 |
+
x = self.dense(x)
|
| 26 |
+
x = torch.tanh(x)
|
| 27 |
+
x = self.dropout(x)
|
| 28 |
+
x = self.out_proj(x)
|
| 29 |
+
return x
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class AgeGenderModel(Wav2Vec2PreTrainedModel):
|
| 33 |
+
def __init__(self, config):
|
| 34 |
+
super().__init__(config)
|
| 35 |
+
self.config = config
|
| 36 |
+
self.wav2vec2 = Wav2Vec2Model(config)
|
| 37 |
+
self.age = ModelHead(config, 1)
|
| 38 |
+
self.gender = ModelHead(config, 3)
|
| 39 |
+
self.init_weights()
|
| 40 |
+
|
| 41 |
+
def forward(self,
|
| 42 |
+
input_values,
|
| 43 |
+
):
|
| 44 |
+
outputs = self.wav2vec2(input_values)
|
| 45 |
+
hidden_states = outputs[0]
|
| 46 |
+
hidden_states = torch.mean(hidden_states, dim=1)
|
| 47 |
+
|
| 48 |
+
logits_age = self.age.forward(hidden_states)
|
| 49 |
+
logits_gender = torch.softmax(self.gender.forward(hidden_states), dim=1)
|
| 50 |
+
|
| 51 |
+
return hidden_states, logits_age, logits_gender
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class AudeeringModel(object):
|
| 55 |
+
"""
|
| 56 |
+
https://arxiv.org/abs/2306.16962
|
| 57 |
+
|
| 58 |
+
https://github.com/audeering/w2v2-age-gender-how-to
|
| 59 |
+
|
| 60 |
+
https://huggingface.co/audeering/wav2vec2-large-robust-6-ft-age-gender
|
| 61 |
+
https://huggingface.co/audeering/wav2vec2-large-robust-24-ft-age-gender
|
| 62 |
+
"""
|
| 63 |
+
def __init__(self, model_path: str):
|
| 64 |
+
self.model_path = model_path
|
| 65 |
+
|
| 66 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 67 |
+
|
| 68 |
+
processor: Wav2Vec2Processor = Wav2Vec2Processor.from_pretrained(self.model_path)
|
| 69 |
+
model = AgeGenderModel.from_pretrained(self.model_path).to(device)
|
| 70 |
+
model.eval()
|
| 71 |
+
|
| 72 |
+
self.device = device
|
| 73 |
+
self.processor = processor
|
| 74 |
+
self.model = model
|
| 75 |
+
|
| 76 |
+
def predict(self, signal: np.ndarray, sample_rate: int) -> dict:
|
| 77 |
+
y = self.processor.__call__(signal, sampling_rate=sample_rate)
|
| 78 |
+
y = y["input_values"][0]
|
| 79 |
+
y = y.reshape(1, -1)
|
| 80 |
+
y = torch.from_numpy(y).to(self.device)
|
| 81 |
+
|
| 82 |
+
_, age, gender = self.model.forward(y)
|
| 83 |
+
|
| 84 |
+
age = age.detach().cpu().numpy().tolist()
|
| 85 |
+
age = age[0][0]
|
| 86 |
+
|
| 87 |
+
gender = gender.detach().cpu().numpy().tolist()
|
| 88 |
+
gender = gender[0]
|
| 89 |
+
|
| 90 |
+
result = {
|
| 91 |
+
"age": round(age, 4),
|
| 92 |
+
"female": round(gender[0], 4),
|
| 93 |
+
"male": round(gender[1], 4),
|
| 94 |
+
"child": round(gender[2], 4),
|
| 95 |
+
}
|
| 96 |
+
return result
|
| 97 |
+
|
| 98 |
+
def __call__(self, *args, **kwargs):
|
| 99 |
+
return self.predict(*args, **kwargs)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
pass
|
toolbox/json/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == '__main__':
|
| 6 |
+
pass
|
toolbox/json/misc.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
from typing import Callable
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def traverse(js, callback: Callable, *args, **kwargs):
|
| 7 |
+
if isinstance(js, list):
|
| 8 |
+
result = list()
|
| 9 |
+
for l in js:
|
| 10 |
+
l = traverse(l, callback, *args, **kwargs)
|
| 11 |
+
result.append(l)
|
| 12 |
+
return result
|
| 13 |
+
elif isinstance(js, tuple):
|
| 14 |
+
result = list()
|
| 15 |
+
for l in js:
|
| 16 |
+
l = traverse(l, callback, *args, **kwargs)
|
| 17 |
+
result.append(l)
|
| 18 |
+
return tuple(result)
|
| 19 |
+
elif isinstance(js, dict):
|
| 20 |
+
result = dict()
|
| 21 |
+
for k, v in js.items():
|
| 22 |
+
k = traverse(k, callback, *args, **kwargs)
|
| 23 |
+
v = traverse(v, callback, *args, **kwargs)
|
| 24 |
+
result[k] = v
|
| 25 |
+
return result
|
| 26 |
+
elif isinstance(js, int):
|
| 27 |
+
return callback(js, *args, **kwargs)
|
| 28 |
+
elif isinstance(js, str):
|
| 29 |
+
return callback(js, *args, **kwargs)
|
| 30 |
+
else:
|
| 31 |
+
return js
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def demo1():
|
| 35 |
+
d = {
|
| 36 |
+
"env": "ppe",
|
| 37 |
+
"mysql_connect": {
|
| 38 |
+
"host": "$mysql_connect_host",
|
| 39 |
+
"port": 3306,
|
| 40 |
+
"user": "callbot",
|
| 41 |
+
"password": "NxcloudAI2021!",
|
| 42 |
+
"database": "callbot_ppe",
|
| 43 |
+
"charset": "utf8"
|
| 44 |
+
},
|
| 45 |
+
"es_connect": {
|
| 46 |
+
"hosts": ["10.20.251.8"],
|
| 47 |
+
"http_auth": ["elastic", "ElasticAI2021!"],
|
| 48 |
+
"port": 9200
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
def callback(s):
|
| 53 |
+
if isinstance(s, str) and s.startswith('$'):
|
| 54 |
+
return s[1:]
|
| 55 |
+
return s
|
| 56 |
+
|
| 57 |
+
result = traverse(d, callback=callback)
|
| 58 |
+
print(result)
|
| 59 |
+
return
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if __name__ == '__main__':
|
| 63 |
+
demo1()
|
toolbox/os/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == '__main__':
|
| 6 |
+
pass
|
toolbox/os/command.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Command(object):
|
| 7 |
+
custom_command = [
|
| 8 |
+
"cd"
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
@staticmethod
|
| 12 |
+
def _get_cmd(command):
|
| 13 |
+
command = str(command).strip()
|
| 14 |
+
if command == "":
|
| 15 |
+
return None
|
| 16 |
+
cmd_and_args = command.split(sep=" ")
|
| 17 |
+
cmd = cmd_and_args[0]
|
| 18 |
+
args = " ".join(cmd_and_args[1:])
|
| 19 |
+
return cmd, args
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def popen(cls, command):
|
| 23 |
+
cmd, args = cls._get_cmd(command)
|
| 24 |
+
if cmd in cls.custom_command:
|
| 25 |
+
method = getattr(cls, cmd)
|
| 26 |
+
return method(args)
|
| 27 |
+
else:
|
| 28 |
+
resp = os.popen(command)
|
| 29 |
+
result = resp.read()
|
| 30 |
+
resp.close()
|
| 31 |
+
return result
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def cd(cls, args):
|
| 35 |
+
if args.startswith("/"):
|
| 36 |
+
os.chdir(args)
|
| 37 |
+
else:
|
| 38 |
+
pwd = os.getcwd()
|
| 39 |
+
path = os.path.join(pwd, args)
|
| 40 |
+
os.chdir(path)
|
| 41 |
+
|
| 42 |
+
@classmethod
|
| 43 |
+
def system(cls, command):
|
| 44 |
+
return os.system(command)
|
| 45 |
+
|
| 46 |
+
def __init__(self):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def ps_ef_grep(keyword: str):
|
| 51 |
+
cmd = "ps -ef | grep {}".format(keyword)
|
| 52 |
+
rows = Command.popen(cmd)
|
| 53 |
+
rows = str(rows).split("\n")
|
| 54 |
+
rows = [row for row in rows if row.__contains__(keyword) and not row.__contains__("grep")]
|
| 55 |
+
return rows
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
pass
|
toolbox/os/environment.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
from dotenv.main import DotEnv
|
| 8 |
+
|
| 9 |
+
from toolbox.json.misc import traverse
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class EnvironmentManager(object):
|
| 13 |
+
def __init__(self, path, env, override=False):
|
| 14 |
+
filename = os.path.join(path, '{}.env'.format(env))
|
| 15 |
+
self.filename = filename
|
| 16 |
+
|
| 17 |
+
load_dotenv(
|
| 18 |
+
dotenv_path=filename,
|
| 19 |
+
override=override
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
self._environ = dict()
|
| 23 |
+
|
| 24 |
+
def open_dotenv(self, filename: str = None):
|
| 25 |
+
filename = filename or self.filename
|
| 26 |
+
dotenv = DotEnv(
|
| 27 |
+
dotenv_path=filename,
|
| 28 |
+
stream=None,
|
| 29 |
+
verbose=False,
|
| 30 |
+
interpolate=False,
|
| 31 |
+
override=False,
|
| 32 |
+
encoding="utf-8",
|
| 33 |
+
)
|
| 34 |
+
result = dotenv.dict()
|
| 35 |
+
return result
|
| 36 |
+
|
| 37 |
+
def get(self, key, default=None, dtype=str):
|
| 38 |
+
result = os.environ.get(key)
|
| 39 |
+
if result is None:
|
| 40 |
+
if default is None:
|
| 41 |
+
result = None
|
| 42 |
+
else:
|
| 43 |
+
result = default
|
| 44 |
+
else:
|
| 45 |
+
result = dtype(result)
|
| 46 |
+
self._environ[key] = result
|
| 47 |
+
return result
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
_DEFAULT_DTYPE_MAP = {
|
| 51 |
+
'int': int,
|
| 52 |
+
'float': float,
|
| 53 |
+
'str': str,
|
| 54 |
+
'json.loads': json.loads
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class JsonConfig(object):
|
| 59 |
+
"""
|
| 60 |
+
将 json 中, 形如 `$float:threshold` 的值, 处理为:
|
| 61 |
+
从环境变量中查到 threshold, 再将其转换为 float 类型.
|
| 62 |
+
"""
|
| 63 |
+
def __init__(self, dtype_map: dict = None, environment: EnvironmentManager = None):
|
| 64 |
+
self.dtype_map = dtype_map or _DEFAULT_DTYPE_MAP
|
| 65 |
+
self.environment = environment or os.environ
|
| 66 |
+
|
| 67 |
+
def sanitize_by_filename(self, filename: str):
|
| 68 |
+
with open(filename, 'r', encoding='utf-8') as f:
|
| 69 |
+
js = json.load(f)
|
| 70 |
+
|
| 71 |
+
return self.sanitize_by_json(js)
|
| 72 |
+
|
| 73 |
+
def sanitize_by_json(self, js):
|
| 74 |
+
js = traverse(
|
| 75 |
+
js,
|
| 76 |
+
callback=self.sanitize,
|
| 77 |
+
environment=self.environment
|
| 78 |
+
)
|
| 79 |
+
return js
|
| 80 |
+
|
| 81 |
+
def sanitize(self, string, environment):
|
| 82 |
+
"""支持 $ 符开始的, 环境变量配置"""
|
| 83 |
+
if isinstance(string, str) and string.startswith('$'):
|
| 84 |
+
dtype, key = string[1:].split(':')
|
| 85 |
+
dtype = self.dtype_map[dtype]
|
| 86 |
+
|
| 87 |
+
value = environment.get(key)
|
| 88 |
+
if value is None:
|
| 89 |
+
raise AssertionError('environment not exist. key: {}'.format(key))
|
| 90 |
+
|
| 91 |
+
value = dtype(value)
|
| 92 |
+
result = value
|
| 93 |
+
else:
|
| 94 |
+
result = string
|
| 95 |
+
return result
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def demo1():
|
| 99 |
+
import json
|
| 100 |
+
|
| 101 |
+
from project_settings import project_path
|
| 102 |
+
|
| 103 |
+
environment = EnvironmentManager(
|
| 104 |
+
path=os.path.join(project_path, 'server/callbot_server/dotenv'),
|
| 105 |
+
env='dev',
|
| 106 |
+
)
|
| 107 |
+
init_scenes = environment.get(key='init_scenes', dtype=json.loads)
|
| 108 |
+
print(init_scenes)
|
| 109 |
+
print(environment._environ)
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if __name__ == '__main__':
|
| 114 |
+
demo1()
|
toolbox/os/other.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import inspect
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def pwd():
|
| 6 |
+
"""你在哪个文件调用此函数, 它就会返回那个文件所在的 dir 目标"""
|
| 7 |
+
frame = inspect.stack()[1]
|
| 8 |
+
module = inspect.getmodule(frame[0])
|
| 9 |
+
return os.path.dirname(os.path.abspath(module.__file__))
|