├── ai ├── common │ ├── params.py │ ├── utils.py │ ├── sysinfo.py │ ├── app_freeze_utils.py │ └── torch_utils.py ├── models │ ├── targets │ │ ├── eva.npy │ │ ├── yara.npy │ │ ├── zeus.npy │ │ ├── blake.npy │ │ └── scarlett.npy │ ├── b_model.pt │ └── model.pt └── spectrogram_conversion │ ├── Makefile │ ├── .gitignore │ ├── data_types.py │ ├── utils │ ├── multiprocessing_utils.py │ ├── audio_utils.py │ └── utils.py │ ├── params.py │ ├── timedscope.py │ ├── perf_counter.py │ ├── voice_conversion.py │ └── inference_rt.py ├── public ├── dark_mode.png └── light_mode.png ├── .gitattributes ├── services └── desktop_app │ ├── assets │ ├── icon.ico │ ├── icon.icns │ ├── avatar-eva.png │ ├── avatar-yara.png │ ├── avatar-zeus.png │ ├── avatar-scarlett.png │ └── MetaVoice Live Logo - Dark Transparent.png │ ├── .gitignore │ ├── src │ ├── supabase.js │ ├── components │ │ ├── Update.css │ │ ├── Conversion.css │ │ ├── PreferencesModal.css │ │ ├── Loading.js │ │ ├── Speaker.js │ │ ├── Profile.js │ │ ├── Login.css │ │ ├── Speaker.css │ │ ├── Update.js │ │ ├── Login.js │ │ ├── SessionFeedbackModal.js │ │ ├── App.js │ │ ├── PreferencesModal.js │ │ └── Conversion.js │ ├── api.ts │ ├── custom.scss │ ├── index.js │ ├── constants.js │ ├── env.js │ └── styles.css │ ├── server │ ├── Makefile │ ├── data_types.py │ ├── portaudio_utils.py │ └── main.py │ ├── index.html │ ├── preload.js │ ├── Makefile │ ├── deploy_ml.py │ ├── deploy_electron.py │ ├── README.md │ ├── package.json │ ├── util.js │ ├── LICENCE.txt │ └── main.js ├── wheels ├── munkipkg-1.0-py3-none-any.whl └── soundfile-0.11.0b3-py2.py3-none-macosx_11_0_arm64.whl ├── Makefile.variable.sample ├── requirements.cuda.txt ├── common └── aws_utils.py ├── Makefile ├── .gitignore ├── README.md ├── debug └── collect_env.py └── LICENSE.txt /ai/common/params.py: -------------------------------------------------------------------------------- 1 | VOCODER_INPUT_SHAPE = (80, 128) 2 | -------------------------------------------------------------------------------- /public/dark_mode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/public/dark_mode.png -------------------------------------------------------------------------------- /public/light_mode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/public/light_mode.png -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pth filter=lfs diff=lfs merge=lfs -text 2 | *.pt filter=lfs diff=lfs merge=lfs -text 3 | -------------------------------------------------------------------------------- /ai/models/targets/eva.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/ai/models/targets/eva.npy -------------------------------------------------------------------------------- /ai/models/targets/yara.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/ai/models/targets/yara.npy -------------------------------------------------------------------------------- /ai/models/targets/zeus.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/ai/models/targets/zeus.npy -------------------------------------------------------------------------------- /ai/models/targets/blake.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/ai/models/targets/blake.npy -------------------------------------------------------------------------------- /ai/models/targets/scarlett.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/ai/models/targets/scarlett.npy -------------------------------------------------------------------------------- /ai/spectrogram_conversion/Makefile: -------------------------------------------------------------------------------- 1 | clean: 2 | rm -rf conversions/** 3 | rm -rf out_infer/** 4 | rm -rf __pycache__/** 5 | -------------------------------------------------------------------------------- /services/desktop_app/assets/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/services/desktop_app/assets/icon.ico -------------------------------------------------------------------------------- /wheels/munkipkg-1.0-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/wheels/munkipkg-1.0-py3-none-any.whl -------------------------------------------------------------------------------- /services/desktop_app/assets/icon.icns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/services/desktop_app/assets/icon.icns -------------------------------------------------------------------------------- /services/desktop_app/assets/avatar-eva.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/services/desktop_app/assets/avatar-eva.png -------------------------------------------------------------------------------- /services/desktop_app/assets/avatar-yara.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/services/desktop_app/assets/avatar-yara.png -------------------------------------------------------------------------------- /services/desktop_app/assets/avatar-zeus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/services/desktop_app/assets/avatar-zeus.png -------------------------------------------------------------------------------- /ai/common/utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def db_to_amp(x) -> np.float32: 5 | return np.power(10.0, x * 0.05).astype(np.float32) 6 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/.gitignore: -------------------------------------------------------------------------------- 1 | **/saved_models 2 | **/out_train 3 | **/out_infer 4 | **/out_eval 5 | **/datasets 6 | **/logs/**.txt 7 | **/originals -------------------------------------------------------------------------------- /services/desktop_app/assets/avatar-scarlett.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/services/desktop_app/assets/avatar-scarlett.png -------------------------------------------------------------------------------- /ai/models/b_model.pt: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:b4b24ab4c5212c98e2b88a5fc5c12b0bb088789b280a5dbf6b9aa8752f013462 3 | size 1262533109 4 | -------------------------------------------------------------------------------- /ai/models/model.pt: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:9abee57727248606e86ab86b5589ce9c9cca6c11aef5eb79181eb50c29286130 3 | size 157848726 4 | -------------------------------------------------------------------------------- /wheels/soundfile-0.11.0b3-py2.py3-none-macosx_11_0_arm64.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/wheels/soundfile-0.11.0b3-py2.py3-none-macosx_11_0_arm64.whl -------------------------------------------------------------------------------- /services/desktop_app/.gitignore: -------------------------------------------------------------------------------- 1 | .cache 2 | dev/ 3 | **/out 4 | **/build 5 | **/pyinstallerbuild 6 | **/dist 7 | **/dist-react 8 | **/myvc 9 | **/*.spec 10 | mvml-*.zip 11 | use-new-version.txt -------------------------------------------------------------------------------- /services/desktop_app/assets/MetaVoice Live Logo - Dark Transparent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/metavoiceio/MetaVoiceLive/HEAD/services/desktop_app/assets/MetaVoice Live Logo - Dark Transparent.png -------------------------------------------------------------------------------- /services/desktop_app/src/supabase.js: -------------------------------------------------------------------------------- 1 | import {createClient} from '@supabase/supabase-js' 2 | import {Keys, Urls} from './env'; 3 | 4 | export const supabase = createClient( 5 | Urls.supabase, 6 | Keys.supabase_anon, 7 | ); 8 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/Update.css: -------------------------------------------------------------------------------- 1 | .logs-container { 2 | max-width: 700px; 3 | margin-left: auto; 4 | margin-right: auto; 5 | } 6 | 7 | .logs { 8 | margin-top: 20px; 9 | } 10 | 11 | .logs-error { 12 | color: rgb(149, 32, 32); 13 | } -------------------------------------------------------------------------------- /services/desktop_app/server/Makefile: -------------------------------------------------------------------------------- 1 | run: 2 | # using the hot reload command for the purposes of server development 3 | uvicorn main:app --port 58000 --reload 4 | 5 | mock: 6 | # using the hot reload command for the purposes of server development 7 | IS_MOCK=true uvicorn main:app --port 58000 --reload 8 | -------------------------------------------------------------------------------- /ai/common/sysinfo.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def get_gpu_cores(): 5 | try: 6 | cores = os.popen("system_profiler -detailLevel basic SPDisplaysDataType | grep 'Total Number of Cores'").read() 7 | cores = int(cores.split(": ")[-1]) 8 | except: 9 | cores = "?" 10 | return cores 11 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/Conversion.css: -------------------------------------------------------------------------------- 1 | .conversion-header { 2 | display: flex; 3 | justify-content: space-between; 4 | margin-top: -10px; 5 | } 6 | .conversion-header-logo { 7 | margin-top: -10px; 8 | margin-bottom: 30px; 9 | margin-left: 24px; 10 | } 11 | .conversion-header-settings { 12 | } -------------------------------------------------------------------------------- /services/desktop_app/src/api.ts: -------------------------------------------------------------------------------- 1 | import { baseSpeakers } from './constants'; 2 | 3 | export async function getSpeakers() { 4 | // might fetch from supabase later 5 | const userSpeakers = await window.electronAPI.getUserSpeakers(); 6 | 7 | return [ 8 | ...userSpeakers, 9 | ...baseSpeakers, 10 | ] 11 | } -------------------------------------------------------------------------------- /services/desktop_app/src/custom.scss: -------------------------------------------------------------------------------- 1 | $highlight: #ff3a27; 2 | 3 | @function tint-color($color, $percentage) { 4 | @return mix(#FFF, $color, $percentage); 5 | } 6 | 7 | $form-range-thumb-bg: $highlight; 8 | $form-range-thumb-active-bg: tint-color($highlight, 30%); 9 | 10 | @import "../node_modules/bootstrap/scss/bootstrap.scss"; 11 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/PreferencesModal.css: -------------------------------------------------------------------------------- 1 | .slider-setting { 2 | display: flex; 3 | justify-content: space-between; 4 | margin-bottom: 10px; 5 | } 6 | .slider-with-min-max { 7 | display: flex; 8 | } 9 | .slider-with-min-max input { 10 | margin-left: 10px; 11 | margin-right: 10px; 12 | width: 150px; 13 | } -------------------------------------------------------------------------------- /services/desktop_app/src/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom/client"; 3 | import App from "./components/App"; 4 | 5 | import './custom.scss'; 6 | import "./styles.css"; 7 | import 'bootstrap-icons/font/bootstrap-icons.css'; 8 | 9 | ReactDOM.createRoot( 10 | document.getElementById('root') 11 | ).render(); 12 | -------------------------------------------------------------------------------- /Makefile.variable.sample: -------------------------------------------------------------------------------- 1 | ##### 2 | # DO NOT EDIT 3 | # This is a sample Makefile.variable file 4 | # Create a local copy of this file, rename to Makefile.variable and update the vars below with their 5 | # appropriate value 6 | ##### 7 | 8 | CONDA_ENV_NAME := mvlive 9 | SITE_PACKAGES := /opt/miniconda3/envs/${CONDA_ENV_NAME}/lib/python3.9/site-packages 10 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/data_types.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class InferencePipelineMode(Enum): 5 | offline_with_overlap = "offline_with_overlap" 6 | online_raw = "online_raw" 7 | online_with_past_future = "online_with_past_future" 8 | online_crossfade = "online_crossfade" 9 | 10 | def __str__(self): 11 | return self.value 12 | -------------------------------------------------------------------------------- /services/desktop_app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | MetaVoice 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/Loading.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Spinner from 'react-bootstrap/Spinner'; 3 | 4 | export default function Loading({isActive, text, fullScreen = true }) { 5 | return ( 6 |
7 | 8 |

{text}

9 |
10 | ); 11 | } 12 | -------------------------------------------------------------------------------- /ai/common/app_freeze_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | from pathlib import Path 4 | 5 | 6 | def get_application_root() -> Path: 7 | if getattr(sys, 'frozen', False): 8 | # If the application is run as a bundle, the PyInstaller bootloader 9 | # extends the sys module by a flag frozen=True and sets the app 10 | # path into variable _MEIPASS'. 11 | return Path(sys._MEIPASS) 12 | else: 13 | return Path(os.environ['METAVOICELIVE_ROOT']) 14 | -------------------------------------------------------------------------------- /ai/common/torch_utils.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import numpy as np 4 | import torch 5 | 6 | 7 | def is_mps_available() -> bool: 8 | try: 9 | return torch.backends.mps.is_available() 10 | except: 11 | return False 12 | 13 | 14 | def get_device() -> torch.device: 15 | device = torch.device('cpu') 16 | 17 | if torch.cuda.is_available(): 18 | device = torch.device('cuda') 19 | 20 | return device 21 | 22 | 23 | def set_seed(seed): 24 | np.random.seed(seed) 25 | random.seed(seed) 26 | torch.manual_seed(seed) 27 | -------------------------------------------------------------------------------- /services/desktop_app/src/constants.js: -------------------------------------------------------------------------------- 1 | import Avatars from '../assets/avatar-*.png'; 2 | 3 | export const SERVER_BASE_URL = 'http://127.0.0.1:58000'; 4 | 5 | export const baseSpeakers = [ 6 | { id: 'zeus', name: 'Zeus', avatar: Avatars.zeus }, 7 | { id: 'eva', name: 'Eva', avatar: Avatars.eva }, 8 | { id: 'scarlett', name: 'Scarlett', avatar: Avatars.scarlett }, 9 | { id: 'yara', name: 'Yara', avatar: Avatars.yara }, 10 | { id: 'blake', name: 'Blake' }, 11 | ] 12 | export const getSpeakerById = (speakers, id) => speakers.find((speaker) => speaker.id === id); 13 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/utils/multiprocessing_utils.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | 3 | 4 | class SharedCounter(object): 5 | """A synchronized shared counter.""" 6 | 7 | def __init__(self, initval=0): 8 | self.count = multiprocessing.Value("i", initval) 9 | 10 | def increment(self, n=1): 11 | """Increment the counter by n (default = 1)""" 12 | with self.count.get_lock(): 13 | self.count.value += n 14 | 15 | @property 16 | def value(self): 17 | """Return the value of the counter""" 18 | return self.count.value 19 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/utils/audio_utils.py: -------------------------------------------------------------------------------- 1 | from typing import Tuple 2 | 3 | import sounddevice as sd 4 | 5 | 6 | def get_audio_io_indices() -> Tuple[int, int]: 7 | def check_device_exists(device_index: int): 8 | try: 9 | sd.query_devices(device_index) 10 | except sd.PortAudioError as e: 11 | print(str(e)) 12 | 13 | print(sd.query_devices()) 14 | input_index = int(input("Enter the input audio device index: ")) 15 | check_device_exists(input_index) 16 | 17 | output_index = int(input("Enter the output audio device index: ")) 18 | check_device_exists(output_index) 19 | 20 | return input_index, output_index 21 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/params.py: -------------------------------------------------------------------------------- 1 | ## Audio 2 | sample_rate = 22050 3 | 4 | ## Mel-filterbank 5 | n_fft = 2048 6 | num_mels = 80 7 | num_samples = 128 # input spect shape num_mels * num_samples 8 | hop_length = 256 # int(0.0125 * sample_rate) # 12.5ms - in line with Tacotron 2 paper 9 | win_length = 1024 # int(0.05 * sample_rate) # 50ms - same reason as above 10 | fmin = 0 11 | fmax = 8000 12 | 13 | # corresponds to 1.486s of audio, or 32768 samples in the time domain. This is the number of samples 14 | # fed into the VC module 15 | MAX_INFER_SAMPLES_VC = num_samples * hop_length 16 | 17 | ## Vocoder 18 | VOCODER_FUTURE_CONTEXT_SPEC_FRAMES = 16 * 2 19 | 20 | SEED = 1234 # numpy & torch PRNG seed 21 | -------------------------------------------------------------------------------- /services/desktop_app/server/data_types.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Dict, List 3 | 4 | from pydantic import BaseModel 5 | 6 | 7 | @dataclass(frozen=True) 8 | class DeviceInfo: 9 | index: int 10 | name: str 11 | max_input_channels: int 12 | max_output_channels: int 13 | default_sample_rate: float 14 | is_default_input: bool 15 | is_default_output: bool 16 | 17 | @property 18 | def is_duplex(self) -> bool: 19 | return bool(self.max_input_channels and self.max_output_channels) 20 | 21 | 22 | DeviceMap = Dict[str, List[DeviceInfo]] 23 | 24 | 25 | class ConvertRequest(BaseModel): 26 | input_device_idx: int 27 | output_device_idx: int 28 | voice_id: str 29 | -------------------------------------------------------------------------------- /requirements.cuda.txt: -------------------------------------------------------------------------------- 1 | librosa==0.8.1 2 | numpy 3 | scikit-learn==1.0.2 4 | scipy==1.8.0 5 | scikit-image 6 | sounddevice==0.4.4 7 | tqdm==4.62.0 8 | webrtcvad==2.0.10 9 | ipdb==0.13.9 10 | gitpython==3.1.27 11 | boto3==1.21.22 12 | wandb==0.12.11 13 | tensorboard==2.7.0 14 | # was giving errors, but should be installed with conda ahead of time 15 | #PyAudio==0.2.11 16 | uvicorn[standard]==0.18.2 17 | fastapi==0.79.0 18 | pydantic==1.9.1 19 | pynput==1.7.6 20 | requests==2.28.1 21 | pyinstaller==5.1 22 | pyinstaller-hooks-contrib==2022.8 23 | coremltools==5.2.0 24 | # version <= 3.20.1 is required for coremltools 25 | protobuf==3.20.1 26 | soundfile==0.10.3.post1 27 | psutil==5.9.1 28 | geocoder==1.38.1 29 | black==22.8.0 30 | isort==5.10.1 31 | python-dotenv 32 | platformdirs==3.8.1 -------------------------------------------------------------------------------- /common/aws_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import boto3 4 | 5 | ACCESS_KEY = None 6 | SECRET_KEY = None 7 | BUCKET = "BUCKET_TO_PUSH_TO" 8 | 9 | S3 = None 10 | if ACCESS_KEY and SECRET_KEY: 11 | S3 = boto3.client( 12 | "s3", 13 | aws_access_key_id=ACCESS_KEY, 14 | aws_secret_access_key=SECRET_KEY, 15 | verify=False, 16 | ) 17 | 18 | 19 | def upload_directory_to_s3(path: str, object_prefix: str) -> None: 20 | if not S3: 21 | return 22 | 23 | assert os.path.exists(path) 24 | 25 | for root, _, files in os.walk(path): 26 | for file in files: 27 | filename = os.path.join(root, file) 28 | S3.upload_file(Filename=filename, Bucket=BUCKET, Key=f"{object_prefix}/{os.path.relpath(filename, path)}") 29 | -------------------------------------------------------------------------------- /services/desktop_app/preload.js: -------------------------------------------------------------------------------- 1 | const { contextBridge, ipcRenderer } = require('electron') 2 | 3 | contextBridge.exposeInMainWorld('electronAPI', { 4 | getAppMode: () => { 5 | return ipcRenderer.invoke('request-app-mode', null); 6 | }, 7 | getAppVersion: () => { 8 | return ipcRenderer.invoke('request-app-version', null); 9 | }, 10 | getUserSpeakers: () => { 11 | return ipcRenderer.invoke('request-user-speakers', null); 12 | }, 13 | getLogs: () => { 14 | return ipcRenderer.invoke('request-logs', null); 15 | }, 16 | onLogInfo: (func) => { 17 | ipcRenderer.on('log-info', (event, ...args) => func(...args)); 18 | }, 19 | onLogError: (func) => { 20 | ipcRenderer.on('log-error', (event, ...args) => func(...args)); 21 | }, 22 | }) -------------------------------------------------------------------------------- /services/desktop_app/src/components/Speaker.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import './Speaker.css'; 3 | 4 | export default function Speaker(props) { 5 | const { 6 | name, 7 | avatar = undefined, 8 | disabled, 9 | selected, 10 | onClick, 11 | } = props; 12 | 13 | return ( 14 | 25 | ); 26 | } -------------------------------------------------------------------------------- /services/desktop_app/Makefile: -------------------------------------------------------------------------------- 1 | include ${METAVOICELIVE_ROOT}/Makefile.variable 2 | 3 | clean-server: 4 | rm -rf dist/ pyinstallerbuild/ 5 | 6 | build-server-windows: clean-server 7 | # NOTE: for Librosa, PyInstaller tries to find all the dependencies, however this folder is not imported but loaded so it misses it. 8 | # We include it in the application bundle through --add-data 9 | # TODO sidroopdaska: remove copying over model once lazy loading has been implemented 10 | pyinstaller -D -n metavoice --workpath pyinstallerbuild \ 11 | -p ${METAVOICELIVE_ROOT} \ 12 | --add-data="${SITE_PACKAGES}/librosa/util/example_data;librosa/util/example_data" \ 13 | --add-data="${SITE_PACKAGES}/_soundfile_data;_soundfile_data" \ 14 | --add-data="${METAVOICELIVE_ROOT}/ai;ai" \ 15 | server/main.py 16 | 17 | rm -rf dist/metavoice/ai/spectrogram_conversion/saved_models 18 | rm -rf dist/metavoice/ai/spectrogram_conversion/originals 19 | 20 | echo local > dist/metavoice/version.txt 21 | 22 | deploy-server: 23 | python deploy_ml.py -------------------------------------------------------------------------------- /ai/spectrogram_conversion/utils/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | import numpy as np 5 | 6 | from ai.spectrogram_conversion.params import * 7 | 8 | 9 | def get_conversion_root() -> str: 10 | if sys.platform == "darwin": 11 | return "/tmp/mvlive/conversion" 12 | else: 13 | return f"C:/Users/{os.getlogin()}/AppData/Local/Temp/mvlive/conversions" 14 | 15 | 16 | def get_ordered_data_from_circular_buffer( 17 | buffer: np.ndarray, buffer_overflow: bool, head: int, segment_len: int = -1 18 | ) -> np.ndarray: 19 | out = None 20 | if segment_len == -1: 21 | # return the entire buffer in order 22 | out = np.concatenate((buffer[head:], buffer[:head]), axis=0) if buffer_overflow else buffer[:head] 23 | return out.flatten() 24 | 25 | if head + segment_len >= len(buffer): 26 | out = np.concatenate( 27 | ( 28 | buffer[head:], 29 | buffer[0:(head + segment_len - len(buffer) + 1)] 30 | ), 31 | axis=0 32 | ) 33 | else: 34 | out = buffer[head : head+segment_len] 35 | return out.flatten() 36 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | include Makefile.variable 2 | 3 | ROOT:=${shell pwd} 4 | SOUNDFILE_DATA := ${SITE_PACKAGES}/_soundfile_data 5 | 6 | BLACK_CONFIG=-t py37 -l 120 7 | BLACK_TARGETS=services/desktop_app/server ai/spectrogram_conversion ai/spectrogram_conversion/utils 8 | ISORT_CONFIG=--atomic -l 120 --trailing-comma --remove-redundant-aliases --multi-line 3 9 | ISORT_TARGETS=services/desktop_app/server ai/spectrogram_conversion ai/spectrogram_conversion/utils 10 | 11 | format: 12 | black $(BLACK_CONFIG) $(BLACK_TARGETS) 13 | isort $(ISORT_CONFIG) $(ISORT_TARGETS) 14 | 15 | setup: 16 | echo 'export METAVOICELIVE_ROOT=${ROOT}' >> ~/.zshrc 17 | echo 'export PYTHONPATH=${ROOT}:$$PYTHONPATH' >> ~/.zshrc 18 | 19 | echo 'export METAVOICELIVE_ROOT=${ROOT}' >> ~/.bashrc 20 | echo 'export PYTHONPATH=${ROOT}:$$PYTHONPATH' >> ~/.bashrc 21 | 22 | install-cuda: 23 | pip install -r requirements.cuda.txt 24 | pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu117 25 | 26 | # if this fails, try via pipwin. Make sure pipwin is within the conda env 27 | pip install pyaudio 28 | 29 | # munkipkg 30 | pip install wheels/munkipkg-1.0-py3-none-any.whl 31 | -------------------------------------------------------------------------------- /services/desktop_app/deploy_ml.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import json 3 | import os 4 | import shutil 5 | 6 | import boto3 7 | from dotenv import load_dotenv 8 | 9 | load_dotenv() 10 | 11 | ml_version = json.load(open("package.json"))["config"]["mlVersion"] 12 | platform = "win32" if os.name == "nt" else "darwin" # matches electron's process.platform 13 | dest_path = f"mvml/mvml-{platform}-{ml_version}.zip" 14 | 15 | print(f"preparing to push to {dest_path} ...") 16 | # add version as version.txt to dist 17 | with open("dist/metavoice/version.txt", "w") as f: 18 | f.write(ml_version) 19 | 20 | print("zipping to mvml-local.zip ...") 21 | shutil.make_archive("mvml-local", "zip", "dist") 22 | 23 | print("creating sha256 checksum ...") 24 | checksum = hashlib.sha256(open("mvml-local.zip", "rb").read()).hexdigest() 25 | print("checksum:", checksum) 26 | 27 | print("initiating s3 ...") 28 | s3c = boto3.client( 29 | "s3", 30 | aws_access_key_id=os.getenv("KEY_AWS_ACCESS"), 31 | aws_secret_access_key=os.getenv("KEY_AWS_SECRET_ACCESS"), 32 | ) 33 | 34 | print("uploading to s3 ...") 35 | s3c.upload_file("mvml-local.zip", "mv-downloads", dest_path) 36 | s3c.upload_file("mvml-local.zip", "mv-downloads", f"{dest_path}.sha256") 37 | 38 | print("done!") 39 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/Profile.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import { useNavigate } from 'react-router-dom'; 3 | import { useSupabaseClient } from '@supabase/auth-helpers-react'; 4 | import Conversion from './Conversion'; 5 | import Loading from './Loading'; 6 | import posthog from 'posthog-js'; 7 | 8 | export default function Profile() { 9 | const supabase = useSupabaseClient(); 10 | const [userMetadata, setUserMetadata] = useState(); 11 | const navigate = useNavigate(); 12 | 13 | useEffect(() => { 14 | // On mount, we check if a user is logged in. 15 | // If so, we'll retrieve the authenticated user's profile. 16 | supabase.auth.getUser() 17 | .then(res => { 18 | if (res.data.user) { 19 | const { user } = res.data; 20 | posthog.identify(user.email, { email: user.email }) 21 | setUserMetadata(user); 22 | } else { 23 | navigate('/login', {replace: true}); 24 | } 25 | }) 26 | .catch(error => { 27 | console.log(`error with fetching metadata. error: ${error}`) 28 | }); 29 | }, []); 30 | 31 | return userMetadata ? ( 32 | 33 | ) : ; 34 | } 35 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/timedscope.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import time 4 | from functools import partial 5 | from logging import Logger 6 | 7 | # disable numba debug logging 8 | numba_logger = logging.getLogger("numba") 9 | numba_logger.setLevel(logging.WARNING) 10 | 11 | DEBUG_PATTERNS = [patt for patt in os.environ.get("DEBUG", "").split(",") if patt] 12 | 13 | 14 | def get_logger(module_name: str): 15 | FORMAT = "%(name)s: %(message)s" 16 | level = logging.INFO 17 | if any(module_name.startswith(patt) for patt in DEBUG_PATTERNS): 18 | level = logging.DEBUG 19 | 20 | logging.basicConfig(level=level, format=FORMAT) 21 | return logging.getLogger(module_name) 22 | 23 | 24 | class TimedScope: 25 | def __init__( 26 | self, 27 | name: str, 28 | logger: Logger, 29 | log_level: int = logging.INFO, 30 | **kwargs, 31 | ): 32 | del kwargs # unused 33 | self._name = name 34 | self._logger = logger 35 | self._log_level = log_level 36 | 37 | def __enter__(self): 38 | self._start_secs = time.time() 39 | return self 40 | 41 | def __exit__(self, exc_type, exc_val, exc_tb): 42 | del exc_tb, exc_type, exc_val # unused 43 | duration_ms = (time.time() - self._start_secs) * 1000 44 | self._logger.log(self._log_level, f"{self._name}: {duration_ms:0.2f}ms") 45 | 46 | 47 | DebugTimedScope = partial(TimedScope, log_level=logging.DEBUG) 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | **/*.DS_Store 3 | **/*.code-workspace 4 | **/*.pickle 5 | **/*.pyc 6 | **/__pycache__ 7 | **/*.tfevents.* 8 | **/*.mp3 9 | **/*.wav 10 | **/*.zip 11 | **/wandb 12 | **/node_modules 13 | **/build 14 | **/dist 15 | **/*.egg-info 16 | **/Makefile.variable 17 | 18 | 19 | # Logs 20 | **/logs 21 | **/*.log 22 | **/npm-debug.log* 23 | **/yarn-debug.log* 24 | **/ yarn-error.log* 25 | 26 | # Runtime data 27 | **/pids 28 | **/*.pid 29 | **/*.seed 30 | **/*.pid.lock 31 | 32 | # Directory for instrumented libs generated by jscoverage/JSCover 33 | **/lib-cov 34 | 35 | # Coverage directory used by tools like istanbul 36 | **/coverage 37 | 38 | # nyc test coverage 39 | **/.nyc_output 40 | 41 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 42 | **/.grunt 43 | 44 | # Bower dependency directory (https://bower.io/) 45 | **/bower_components 46 | 47 | # node-waf configuration 48 | **/.lock-wscript 49 | 50 | # Compiled binary addons (http://nodejs.org/api/addons.html) 51 | **/build/Release 52 | 53 | # Optional npm cache directory 54 | **/.npm 55 | 56 | # Optional eslint cache 57 | **/.eslintcache 58 | 59 | # Optional REPL history 60 | **/.node_repl_history 61 | 62 | # Output of 'npm pack' 63 | **/*.tgz 64 | 65 | # Yarn Integrity file 66 | **/.yarn-integrity 67 | 68 | # dotenv environment variables file 69 | **/.env 70 | 71 | # electron cache 72 | **/.cache 73 | 74 | # dev assets 75 | services/desktop_app/dev -------------------------------------------------------------------------------- /services/desktop_app/src/components/Login.css: -------------------------------------------------------------------------------- 1 | .auth-container { 2 | width: 360px; 3 | min-height: 500px; 4 | overflow-x: hidden; 5 | } 6 | .auth-logo { 7 | width: 120px; 8 | margin: 0 120px; 9 | margin-bottom: 40px; 10 | } 11 | 12 | .auth-button { 13 | color: #fff !important; 14 | font-weight: 500 !important; 15 | border-radius: 0.375rem !important; 16 | font-size: 1rem !important; 17 | padding: 0.75rem 1.25rem !important; 18 | display: inline-flex !important; 19 | justify-content: center !important; 20 | width: 100% !important; 21 | text-align: center !important; 22 | } 23 | .auth-button:focus { 24 | outline: none !important; 25 | box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5) !important; 26 | } 27 | 28 | .auth-input { 29 | background-color: #1f2937 !important; 30 | padding: 0.5rem 1rem !important; 31 | border-radius: 0.375rem !important; 32 | color: #fff !important; 33 | } 34 | .auth-input::placeholder { 35 | color: #9ca3af !important; 36 | } 37 | .auth-input:focus { 38 | outline: none !important; 39 | box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5) !important; 40 | } 41 | 42 | .auth-label { 43 | text-align: left !important; 44 | margin-bottom: 0.25rem !important; 45 | letter-spacing: 0.025em !important; 46 | } 47 | 48 | .auth-anchor { 49 | color: #9ca3af !important; 50 | text-decoration: none !important; 51 | } 52 | .auth-anchor:hover { 53 | text-decoration: underline !important; 54 | } 55 | 56 | .auth-divider { 57 | background-color: #1f2937 !important; 58 | height: 1px !important; } 59 | 60 | -------------------------------------------------------------------------------- /services/desktop_app/deploy_electron.py: -------------------------------------------------------------------------------- 1 | # cleans the build directory from mvml and zips the electron build. 2 | # assumes `npm run react-package && npm run electron-package-build` has been run 3 | 4 | import os 5 | import json 6 | 7 | from dotenv import load_dotenv 8 | load_dotenv() 9 | 10 | import boto3 11 | import shutil 12 | 13 | def deploy(): 14 | el_version = json.load(open("package.json"))["version"] 15 | # see https://github.com/electron/update.electronjs.org/blob/main/src/asset-platform.js 16 | platform = 'win32-x64' if os.name == 'nt' else 'darwin' # matches electron's process.platform 17 | src_path = f"out/MetaVoice-{platform}" # TODO test works for other platforms 18 | dest_path = f"out/MetaVoice-{el_version}-{platform}" 19 | 20 | print(f'cleaning {src_path} ...') 21 | # remove dist folder 22 | if os.path.exists(src_path + "/resources/app/dist"): 23 | print('- removing /resources/app/dist ...') 24 | shutil.rmtree(src_path + "/resources/app/dist") 25 | 26 | # remove mvml-*.zip files 27 | for f in os.listdir(src_path + "/resources/app"): 28 | if f.startswith("mvml-") and f.endswith(".zip"): 29 | print('- removing /resources/app/' + f + ' ...') 30 | os.remove(src_path + "/resources/app/" + f) 31 | 32 | print(f'zipping to {dest_path}.zip ...') 33 | 34 | shutil.make_archive(dest_path, "zip", src_path) 35 | 36 | # TODO automatic upload mvml if new version? 37 | # TODO automatic upload to github? 38 | 39 | print('done! You can upload it as an appendix to the github release.') 40 | 41 | if __name__ == '__main__': 42 | deploy() -------------------------------------------------------------------------------- /services/desktop_app/src/components/Speaker.css: -------------------------------------------------------------------------------- 1 | .speaker { 2 | display: flex; 3 | flex-direction: column; 4 | align-items: center; 5 | text-align: center; 6 | background-color: transparent; 7 | border: none; 8 | color: #999; 9 | font-size: 1.5em; 10 | padding: 0.25em; 11 | padding-top: 20px; 12 | } 13 | .speaker:not(.speaker--selected,.speaker--disabled):hover { 14 | color: #aaa; 15 | } 16 | .speaker--selected { 17 | color: #eee; 18 | } 19 | .speaker--disabled { 20 | color: #ccc; 21 | cursor: not-allowed; 22 | filter: greyscale(100%); 23 | } 24 | .speaker-avatar { 25 | border-radius: 50%; 26 | height: 80px; 27 | width: 80px; 28 | vertical-align: middle; 29 | box-shadow: 0 0 5px #8885; 30 | filter: grayscale(50%); 31 | } 32 | .speaker--selected .speaker-avatar { 33 | width: 112px; 34 | height: 112px; 35 | border: 2px solid #eee; 36 | box-shadow: 0 0 5px #eee; 37 | margin-top: -2px; 38 | filter: none; 39 | } 40 | .speaker:not(.speaker--selected,.speaker--disabled):hover .speaker-avatar { 41 | width: 84px; 42 | height: 84px; 43 | box-shadow: 0 0 10px #eee8; 44 | filter: grayscale(25%); 45 | } 46 | .speaker:not(.speaker--selected,.speaker--disabled):hover .speaker-avatar--placeholder { 47 | font-size: calc(50px * (84/80)); 48 | line-height: 84px; 49 | } 50 | .speaker-avatar--placeholder { 51 | background-color: #ccc; 52 | color: #999 !important; 53 | font-size: 50px; 54 | line-height: 80px; 55 | } 56 | .speaker--selected .speaker-avatar--placeholder { 57 | font-size: calc(50px * (112/80)); 58 | line-height: 112px; 59 | } 60 | .speaker-name { 61 | display: inline-block; 62 | margin-top: 10px; 63 | } -------------------------------------------------------------------------------- /services/desktop_app/src/env.js: -------------------------------------------------------------------------------- 1 | const env = getEnv(); 2 | 3 | export class Config { 4 | static production = env.NODE_ENV === "production"; 5 | } 6 | export class Keys { 7 | static supabase_anon = env.KEY_SUPABASE_ANON.trim(); 8 | static posthog = env.KEY_POSTHOG.trim(); 9 | } 10 | export class Urls { 11 | static supabase = env.URL_SUPABASE.trim(); 12 | static posthog = env.URL_POSTHOG.trim(); 13 | } 14 | 15 | // for now we can hardcode values, but soon we'll want to open source and hide values (will need to erase git history!). 16 | // So we'll need to get values from an env file, that should apply during build as well. That's not trivial so won't do now. 17 | // But then this function will just be `return process.env` 18 | function getEnv() { 19 | const localEnv = ` 20 | NODE_ENV=production 21 | 22 | KEY_SUPABASE_ANON=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJ4aGFrZ2ppYnFrb2p5b2NmcGp0Iiwicm9sZSI6ImFub24iLCJpYXQiOjE2NzQwNjA3MTAsImV4cCI6MTk4OTYzNjcxMH0.CLhNEQT7p75v-hq0oCraB6Xc8ciG18pkVmLDWTjrsAU 23 | KEY_POSTHOG=phc_SQPRajl0Np93cxPSsBBTV1E7VlMcpBotEjGrbjAOeJI 24 | 25 | URL_SUPABASE=https://rxhakgjibqkojyocfpjt.supabase.co 26 | URL_POSTHOG=https://p-api.themetavoice.xyz 27 | ` 28 | .trim() 29 | .split("\n") 30 | .map((line) => line.trim()) 31 | .filter((line) => line.length > 0) 32 | .map((line) => line.split("=")) 33 | .map((line) => [line[0], line.slice(1).join("=")]) 34 | .map((line) => [line[0], line[1].replace(/(^"|"$)/g, "")]) 35 | .reduce((acc, [key, value]) => { 36 | acc[key] = value; 37 | return acc; 38 | }, {}); 39 | 40 | return { 41 | ...localEnv, 42 | // should be added to preload file in the future 43 | //...process.env, 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/Update.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from "react"; 2 | import './Update.css'; 3 | 4 | import Loading from './Loading' 5 | 6 | export default function Update() { 7 | const [logs, setLogs] = useState([]); 8 | 9 | useEffect(() => { 10 | window.electronAPI.getLogs().then((arg) => { 11 | setLogs(arg); 12 | }); 13 | window.electronAPI.onLogInfo(({ msg }) => { 14 | setLogs((logs) => [...logs, { type: 'log', msg }]); 15 | }); 16 | window.electronAPI.onLogError(({ msg, error }) => { 17 | setLogs((logs) => [...logs, { type: 'error', msg, error }]); 18 | }); 19 | }, []); 20 | 21 | return ( 22 |
23 |
24 | {logs.length > 0 25 | ? ( 26 | <> 27 | 28 |
29 | An update is required and is being processed. Make sure you have at least 5GB of available space on disk, this may take a few minutes. Please keep this window open, the app will restart by itself once it's done. 30 | 31 | ) 32 | : ( 33 | <> 34 | This is the page where we show logs for updates. There are currently no logs. If you think you are here by mistake, please refresh the page with Ctrl+R' 35 | 36 | ) 37 | } 38 |
39 |
40 |             {logs.map((log, i) => {
41 |                 if (log.type === 'log') {
42 |                     return 
{log.msg}
; 43 | } else { 44 | return
{log.msg} {log.error && log.error.toString()}
; 45 | } 46 | })} 47 |
48 |
49 | ) 50 | } 51 | -------------------------------------------------------------------------------- /services/desktop_app/README.md: -------------------------------------------------------------------------------- 1 | # MetaVoice Live: Real-time Voice Conversion desktop app 2 | 3 | Cross-platform native desktop app that allows the user to convert their voice in real-time to a target voice. 4 | 5 | 6 | ## How to run? 7 | * Install dependencies: `npm install` 8 | 9 | * Dev mode: `npm start` 10 | * Prod mode: 11 | * Package server: `make build-server-windows` 12 | * Package electron: `npm run package` 13 | 14 | ### Adding a voice 15 | You should add the .npy file we provide to `%APPDATA%/speakers/`, on windows. 16 | -- add some guidance here 17 | 18 | ## Deploy 19 | ### MVML - MetaVoice ML server 20 | 21 | ```sh 22 | make build-server-windows 23 | 24 | # manually update `config.mlVersion` in package.json 25 | 26 | # this will create the zip file and upload it to s3 27 | python deploy_ml.py 28 | ``` 29 | 30 | That's all. A new MVML server deployment doesn't automatically cause older user instances to update, you'll need to deploy the electron package 31 | with the updated `config > mlVersion` in package.json 32 | 33 | ### Electron 34 | ```sh 35 | # If anything in the frontend changed, including assets/html/css/react. Also on first build 36 | npm run react-package 37 | 38 | # manually update `version` in package.json 39 | 40 | # populates the out/ dir 41 | npm run electron-package-win 42 | 43 | # cleans the destination dir from evidence of usage, and zips the file with the right version. 44 | # To be safe when deploying, you might want to rebuild after usage, or MVML and other files might be included 45 | python deploy_electron.py 46 | ``` 47 | 48 | Now you can use the zip file at the location specified in the logs of the last command, and manually upload it as a latest release to https://github.com/metavoicexyz/MetaVoiceLive/releases . 49 | 50 | Don't change the file name. Make sure the release tag is valid semver, e.g. `v1.2.3`. 51 | 52 | The update mechanism is dependent on `metavoicexyz/MetaVoiceLive` being the repo you release to, and this repo being public. The repo itself doesn't need to contain any code. -------------------------------------------------------------------------------- /services/desktop_app/src/components/Login.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { useNavigate, useLocation } from 'react-router-dom'; 3 | import { useAtom } from 'jotai'; 4 | import { Auth } from "@supabase/auth-ui-react" 5 | import { supabase } from '../supabase'; 6 | import { appModeAtom } from './App'; 7 | import logo from '../images/image.json'; 8 | 9 | import './Login.css' 10 | 11 | // flow: 12 | // 1. login/sign up via supabase 13 | // 2. onAuthStateChange redirects to `/` 14 | 15 | export default function Login() { 16 | const navigate = useNavigate(); 17 | const [appMode,] = useAtom(appModeAtom); 18 | 19 | useEffect(() => { 20 | if (appMode === 'update') { 21 | // how did we get here? Happens during updates 22 | navigate('/update'); 23 | } 24 | }, [appMode]) 25 | 26 | return ( 27 |
28 | logo 32 | 71 |
72 | ) 73 | } 74 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/perf_counter.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import time 3 | from collections import deque 4 | from functools import partial 5 | from logging import Logger 6 | 7 | import numpy as np 8 | 9 | 10 | class PerfCounter: 11 | counter_index = {} 12 | q_ms_index = {} 13 | 14 | def __init__( 15 | self, 16 | name: str, 17 | logger: Logger, 18 | log_level: int = logging.INFO, 19 | window_len=10, 20 | ) -> None: 21 | if name not in PerfCounter.counter_index: 22 | PerfCounter.counter_index[name] = 0 23 | if name not in PerfCounter.q_ms_index: 24 | PerfCounter.q_ms_index[name] = deque(maxlen=window_len) 25 | 26 | self._name = name 27 | self._logger = logger 28 | self._log_level = log_level 29 | self._window_len = window_len 30 | self._start_sec = None 31 | 32 | def __enter__(self): 33 | self._start_sec = time.time() 34 | return self 35 | 36 | def __exit__(self, exc_type, exc_val, exc_tb): 37 | del exc_type, exc_val, exc_tb # unused 38 | 39 | duration_ms = (time.time() - self._start_sec) * 1000 40 | PerfCounter.q_ms_index[self._name].append(duration_ms) 41 | 42 | counter = PerfCounter.counter_index[self._name] 43 | counter = (counter + 1) % self._window_len 44 | 45 | if counter >= self._window_len - 1: 46 | q = PerfCounter.q_ms_index[self._name] 47 | mean = np.mean(q) 48 | pct_95 = np.percentile(q, 95) 49 | max = np.max(q) 50 | 51 | spacing = " " * (20 - len(self._name)) 52 | self._logger.log( 53 | self._log_level, 54 | f"{self._name}: {spacing}mean: {mean:0.2f}ms \tpct_95: {pct_95:0.2f}ms \tmax: {max:0.2f}ms", 55 | ) 56 | 57 | PerfCounter.counter_index[self._name] = counter 58 | 59 | 60 | DebugPerfCounter = partial(PerfCounter, log_level=logging.DEBUG) 61 | 62 | 63 | if __name__ == "__main__": 64 | from timedscope import get_logger 65 | 66 | LOGGER = get_logger(__name__) 67 | 68 | for i in range(20): 69 | with PerfCounter("foo", LOGGER): 70 | a = 1 + 1 71 | time.sleep(0.1) 72 | 73 | with PerfCounter("bar", LOGGER): 74 | a = 1 + 1 75 | time.sleep(0.05) 76 | -------------------------------------------------------------------------------- /services/desktop_app/server/portaudio_utils.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, List 2 | 3 | import sounddevice as sd 4 | from data_types import DeviceInfo 5 | 6 | 7 | def get_devices(mode) -> Dict[str, List[DeviceInfo]]: 8 | sd._terminate() 9 | sd._initialize() 10 | 11 | inputs = [] 12 | outputs = [] 13 | excludeInputs = [] 14 | excludeOutputs = [] 15 | 16 | for index, dinfo in enumerate(sd.query_devices()): 17 | # If multiple portaudio interface APIs exist, chooses the first one 18 | # to prevent multiple devices being shown to the user (some of which may not work) 19 | # Refs: 20 | # 1. http://files.portaudio.com/docs/v19-doxydocs/api_overview.html 21 | # 2. https://stackoverflow.com/questions/20943803/pyaudio-duplicate-devices 22 | if dinfo["hostapi"] == 0: 23 | device_info = DeviceInfo( 24 | **{ 25 | "name": dinfo["name"], 26 | "index": index, 27 | "max_input_channels": dinfo["max_input_channels"], 28 | "max_output_channels": dinfo["max_output_channels"], 29 | "default_sample_rate": dinfo["default_samplerate"], 30 | "is_default_input": index == sd.default.device[0], 31 | "is_default_output": index == sd.default.device[1], 32 | } 33 | ) 34 | 35 | if device_info.is_duplex: 36 | inputs.append(device_info) 37 | outputs.append(device_info) 38 | elif device_info.max_input_channels: 39 | inputs.append(device_info) 40 | elif device_info.max_output_channels: 41 | outputs.append(device_info) 42 | else: 43 | raise ValueError(f"Unknown device, {str(device_info)}") 44 | 45 | # There are three modes: 46 | # i) all - contains all devices 47 | # experimental & prod both remove 'system devices' like MetaVoice Cable Input & ZoomAudioDevice 48 | # ii) experimental - removes krisp speaker from output device, to enable krisp microphone as input 49 | # iii) prod - removes krisp microphones on top of experimental 50 | if mode != "all": 51 | excludeInputs.extend(["MetaVoice Cable", "ZoomAudioDevice"]) 52 | excludeOutputs.extend(["ZoomAudioDevice"]) 53 | 54 | if mode == "experimental": 55 | excludeOutputs.extend(["krisp speaker"]) 56 | elif mode == "prod": 57 | excludeInputs.extend(["krisp microphone"]) 58 | excludeOutputs.extend(["krisp speaker"]) 59 | 60 | inputs = [d for d in inputs if d.name not in excludeInputs] 61 | outputs = [d for d in outputs if d.name not in excludeOutputs] 62 | 63 | return { 64 | "inputs": inputs, 65 | "outputs": outputs, 66 | } 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MetaVoice 2 | 3 | 4 | [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/OnusFM.svg?style=social&label=@metavoiceio)](https://twitter.com/metavoiceio) 5 | ![Static Badge](https://img.shields.io/badge/repo-inactive-red) 6 | 7 | > 🔗 • [Getting started](#-getting-started) • [Installation](https://discord.com/channels/902229215993282581/1133486389661536297) • [Tips, Tricks & FAQ](https://bit.ly/metavoice-faqs) 8 | 9 |
10 |

11 | 12 | 13 | logo banner 14 | 15 |

16 |
17 | 18 | 19 | Welcome to **MetaVoice Live, our real-time AI voice changer**! Live converts your voice while preserving your intonations, emotions, and accent. 20 | 21 | We are open-sourcing our code to give the community the freedom to make their own improvements. This repository contains source code for: 22 | - Our ML model inference on Windows & Nvidia GPUs, and, 23 | - User-facing desktop app 24 | 25 | 26 | ## 💻 Getting started 27 | 28 | > Please use Windows as the development environment. We recommend using [Cmder](https://cmder.app/) as the terminal of choice. 29 | 30 | 1. Run `conda create -n mvc python=3.10 -c conda-forge` and `conda activate mvc` 31 | 2. Copy `Makefile.variable.sample`, rename to `Makefile.variable` & update the vars with their appropriate value. Make sure the site-packages directory exists, or adjust it. 32 | 3. Run `make setup` 33 | 4. Run `make install-cuda` 34 | 5. Add the windows env variable `set METAVOICELIVE_ROOT=%cd%` 35 | 6.
36 | Setup Git LFS 37 |
    38 |
  • Install Git LFS for Windows here
  • 39 |
  • Initialise Git LFS within the repository by running: git lfs install
  • 40 |
  • Pull the model weights via: git lfs pull
  • 41 |
42 |
43 | 44 | (Optional) You might also want to copy `.env.sample` into `.env` and fill those values if you can. 45 | 46 | ### 📖 Repo structure 47 | * `ai/` -> ML model weights & inferencing pipeline 48 | * `services/desktop_app` -> electron application, see its README.md 49 | 50 | 51 | ## 🛠️ Get involved 52 | 53 | We welcome PRs & issues. If you have questions, please mention @sidroopdaska or @towc 54 | 55 | Some ideas for first PRs: 56 | - Port `inference_rt.py` -> C++ 57 | - Streamline the Electron app build & release process 58 | - Add support to package Live for Mac 59 | 60 | 🙏 If you come across something sensitive, e.g. vulnerabilities or access keys, please let us know privately on 📧 [hello@themetavoice.xyz](mailto:hello@themetavoice.xyz) first & give us 2 weeks to resolve it. 61 | 62 | 63 | ## 🤗 Community 64 | 65 | - [Twitter](https://twitter.com/themetavoice) 66 | 67 | 68 | ## © License 69 | 70 | MetaVoice Live is licensed under the [GPL-3.0 license](./LICENSE.txt). 71 | 72 | Please contact us at 📧 [hello@themetavoice.xyz](mailto:hello@themetavoice.xyz) to request access to a larger version of the model. 73 | 74 | ## ⚠️ Disclaimer 75 | 76 | MetaVoice does not take responsibility for any output generated. Please use responsibly. 77 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/voice_conversion.py: -------------------------------------------------------------------------------- 1 | import abc 2 | import argparse 3 | import os 4 | import tempfile 5 | from abc import abstractmethod 6 | from multiprocessing import Value 7 | 8 | import librosa 9 | import numpy as np 10 | import platformdirs 11 | import soundfile as sf 12 | import torch 13 | 14 | import ai.spectrogram_conversion.params as params 15 | from ai.common.app_freeze_utils import get_application_root 16 | from ai.common.torch_utils import get_device 17 | from ai.spectrogram_conversion.utils.utils import get_conversion_root 18 | 19 | # electron prefers the roaming folder for user data 20 | USER_DATA_ROOT = os.path.join(platformdirs.user_data_dir("MetaVoice", roaming=True), "..") 21 | MODELS_ROOT = os.path.join(get_application_root(), "ai/models") 22 | USER_MODELS_ROOT = os.path.join(USER_DATA_ROOT, "speakers") 23 | 24 | 25 | class ModelConversionPipeline(abc.ABC): 26 | def __init__(self, opt: argparse.Namespace): 27 | self._opt = opt 28 | self.p_sampling_rate = 16000 29 | self.pp_sampling_rate = 24000 30 | 31 | self.device = get_device() 32 | self.mac_silicon_device = torch.backends.mps.is_available() 33 | 34 | # TODO: add brancing logic for windows vs mac. 35 | self.model = torch.jit.load(os.path.join(MODELS_ROOT, "model.pt")).to(self.device) 36 | self._load_model_preprocessor() 37 | 38 | self._set_target(self._opt.target_speaker) 39 | self.tmp_file = os.path.join(get_conversion_root(), os.urandom(8).hex() + ".wav") 40 | 41 | def _set_target(self, speaker_id: str): 42 | path_model = os.path.join(MODELS_ROOT, f"targets/{speaker_id}.npy") 43 | path = path_model 44 | 45 | if not os.path.exists(path): 46 | path_user = os.path.join(USER_MODELS_ROOT, f"{speaker_id}.npy") 47 | path = path_user 48 | 49 | if not os.path.exists(path): 50 | raise FileNotFoundError(f"Target speaker {speaker_id} not found in {path_model} or {path_user}.") 51 | 52 | self.target = np.load(path) 53 | self.target = torch.from_numpy(self.target).unsqueeze(0).to(self.device) 54 | 55 | def _load_model_preprocessor(self): 56 | if self.mac_silicon_device: 57 | import coremltools as ct 58 | 59 | self.pmodel = ct.models.MLModel(os.path.join(MODELS_ROOT, "model.mlpackage")) 60 | else: 61 | # TODO: add branching logic for windows vs mac 62 | self.pmodel = torch.jit.load(os.path.join(MODELS_ROOT, "b_model.pt")).to(self.device) 63 | 64 | def infer(self, wav: np.ndarray) -> np.ndarray: 65 | # TODO: fix hack. we write incoming 22050Hz audio into 16khz file, use preprocessor, then inference which 66 | # returns file at 24kHz, and write it back into 22050Hz file as expected for rest of the pipeline. 67 | with torch.no_grad(): 68 | sf.write(self.tmp_file, wav, params.sample_rate) 69 | 70 | wav_src, _ = librosa.load(self.tmp_file, sr=self.p_sampling_rate) 71 | if not self.mac_silicon_device: 72 | wav_src = torch.from_numpy(wav_src).unsqueeze(0).to(self.device) 73 | c = self.pmodel(wav_src.squeeze(1)) 74 | else: 75 | c = self.pmodel.predict({"input_values": wav_src[np.newaxis, :]})["var_3641"] 76 | c = torch.from_numpy(c).to(self.device) 77 | 78 | audio = self.model(c, self.target) 79 | audio = audio[0][0].data.cpu().float().numpy() 80 | 81 | sf.write(self.tmp_file, audio, self.pp_sampling_rate) 82 | 83 | out, _ = librosa.load(self.tmp_file, sr=params.sample_rate) 84 | os.remove(self.tmp_file) 85 | 86 | return out 87 | 88 | @abstractmethod 89 | def run(self, wav: np.ndarray): 90 | pass 91 | -------------------------------------------------------------------------------- /services/desktop_app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "metavoice", 3 | "productName": "MetaVoice", 4 | "version": "0.2.9", 5 | "description": "Convert your voice in real-time to a unique voice identity", 6 | "main": "main.js", 7 | "scripts": { 8 | "react-start": "parcel -p 3000 index.html --out-dir dev", 9 | "react-package": "parcel build index.html --no-source-maps --no-minify --out-dir dist-react --public-url ./", 10 | "start": "concurrently \"npm run react-start\" \"wait-on http://localhost:3000 && cross-env NODE_ENV=dev electron .\"", 11 | "electron-package-win": "electron-forge package", 12 | "electron-package-mac": "electron-forge package --arch=arm64 --platform=darwin", 13 | "package-mac": "make build-server-mac && npm run react-package && npm run electron-package-mac", 14 | "package-win": "make build-server-windows && npm run react-package && npm run electron-package-win", 15 | "deploy": "python deploy_ml.py && python deploy_electron.py", 16 | "build-and-deploy-win": "npm run package-win && npm run deploy" 17 | }, 18 | "author": "MetaVoice", 19 | "license": "ISC", 20 | "devDependencies": { 21 | "@electron-forge/cli": "^6.0.0-beta.61", 22 | "@electron-forge/maker-deb": "^6.0.0-beta.61", 23 | "@electron-forge/maker-dmg": "^6.0.0-beta.61", 24 | "@electron-forge/maker-pkg": "^6.0.0-beta.61", 25 | "@electron-forge/maker-rpm": "^6.0.0-beta.61", 26 | "@electron-forge/maker-squirrel": "^6.0.0-beta.61", 27 | "@electron-forge/maker-zip": "^6.0.0-beta.61", 28 | "concurrently": "^7.3.0", 29 | "cross-env": "^7.0.3", 30 | "electron": "^25.2.0", 31 | "parcel-bundler": "^1.12.5", 32 | "sass": "^1.54.8", 33 | "typescript": "^5.1.6", 34 | "wait-on": "^6.0.1" 35 | }, 36 | "dependencies": { 37 | "@supabase/auth-helpers-react": "^0.4.0", 38 | "@supabase/auth-ui-react": "^0.4.2", 39 | "@supabase/auth-ui-shared": "^0.1.6", 40 | "@supabase/supabase-js": "^2.26.0", 41 | "bootstrap": "^5.2.0", 42 | "bootstrap-icons": "^1.9.1", 43 | "electron-log": "^4.4.8", 44 | "electron-squirrel-startup": "^1.0.0", 45 | "electron-window-state": "^5.0.3", 46 | "express": "^4.18.2", 47 | "jotai": "^2.2.1", 48 | "posthog-js": "^1.68.5", 49 | "react": "^18.2.0", 50 | "react-bootstrap": "^2.5.0", 51 | "react-dom": "^18.2.0", 52 | "react-router-dom": "^6.3.0", 53 | "request": "^2.88.2", 54 | "systeminformation": "^5.18.6", 55 | "unzipper": "^0.10.14" 56 | }, 57 | "config": { 58 | "mlVersion": "0.1.4", 59 | "forge": { 60 | "packagerConfig": { 61 | "icon": "./assets/icon", 62 | "ignore": [ 63 | "# these are regular expressions accepting partial matches to path, with root at same level of package.json, node_modules files included", 64 | "/Makefile", 65 | "\\.spec$", 66 | "\\.plist", 67 | "\\.cer", 68 | "\\.certSigningRequest", 69 | "\\.gitignore", 70 | "\\.vscode/*", 71 | "\\.dmg", 72 | "\\.pkg", 73 | "^/\\.env$", 74 | "^/deploy_.*\\.py$", 75 | "^/__pycache__$", 76 | "^/README.md$", 77 | "^/conversions$", 78 | "^/\\.cache$", 79 | "^/dev$", 80 | "^/dist$", 81 | "^/mvml-.*\\.zip", 82 | "^/src$", 83 | "^/!src.*", 84 | "^/.*\\.bak", 85 | "^/server$", 86 | "^/server-functions$", 87 | "^/pyinstallerbuild$", 88 | "^/use-new-version.txt$" 89 | ] 90 | }, 91 | "makers": [ 92 | { 93 | "name": "@electron-forge/maker-squirrel", 94 | "config": { 95 | "name": "MetaVoice" 96 | } 97 | }, 98 | { 99 | "name": "@electron-forge/maker-zip", 100 | "platforms": [ 101 | "darwin" 102 | ] 103 | }, 104 | { 105 | "name": "@electron-forge/maker-dmg", 106 | "config": { 107 | "name": "MetaVoice", 108 | "format": "ULFO" 109 | } 110 | }, 111 | { 112 | "name": "@electron-forge/maker-deb", 113 | "config": {} 114 | }, 115 | { 116 | "name": "@electron-forge/maker-rpm", 117 | "config": {} 118 | } 119 | ] 120 | } 121 | } 122 | } -------------------------------------------------------------------------------- /services/desktop_app/src/components/SessionFeedbackModal.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import Form from 'react-bootstrap/Form'; 3 | import Button from 'react-bootstrap/Button'; 4 | import Modal from 'react-bootstrap/Modal'; 5 | import Spinner from 'react-bootstrap/Spinner'; 6 | import OverlayTrigger from 'react-bootstrap/OverlayTrigger'; 7 | import Tooltip from 'react-bootstrap/Tooltip'; 8 | import { SERVER_BASE_URL } from '../constants'; 9 | 10 | // todo error handling 11 | export default function SessionFeedbackModal({shouldDisableButton}) { 12 | const [show, setShow] = useState(false); 13 | const [duration, setDuration] = useState(0) // in seconds 14 | const [feedback, setFeedback] = useState("") 15 | const [sendInProgress, setSendInProgress] = useState(false); 16 | const [error, setError] = useState(null); 17 | 18 | const handleClose = () => { 19 | if (sendInProgress) return; 20 | setShow(false); 21 | } 22 | 23 | const handleShow = () => setShow(true); 24 | const handleRadioChange = event => setDuration(parseInt(event.target.value)); 25 | const handleTextAreaChange = event => setFeedback(event.target.value); 26 | 27 | const handleSubmit = (_event) => { 28 | fetch(`${SERVER_BASE_URL}/feedback?content=${feedback}&duration=${duration}`, { method: 'GET', keepalive: true }) 29 | .then(_response => { 30 | setSendInProgress(false); 31 | setShow(false); 32 | }).catch(_error => { 33 | console.log(_error); 34 | setError('Something went wrong. Please try again.'); 35 | setSendInProgress(false); 36 | }); 37 | setSendInProgress(true); 38 | } 39 | 40 | return
41 |
42 | 45 |
46 | 47 | 48 | 49 | Share Feedback 50 | 51 | 52 | 59 | 60 | Audio length:   61 | 69 | 77 | 85 | 86 | 90 | 94 | By clicking send, you agree to share your data with MetaVoice striclty for the purposes of providing you a better voice & app experience. 95 | 96 | } 97 | > 98 | 99 | 100 | {error &&

{error}

} 101 |
102 |
103 |
104 | } 105 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/App.js: -------------------------------------------------------------------------------- 1 | import {SessionContextProvider} from '@supabase/auth-helpers-react'; 2 | import React, { useEffect } from 'react'; 3 | import { Route, MemoryRouter, Routes, useNavigate, useLocation } from 'react-router-dom'; 4 | import posthog from 'posthog-js'; 5 | import { atom, useAtom } from 'jotai'; 6 | import { supabase } from '../supabase'; 7 | import { Keys, Urls } from '../env'; 8 | 9 | // Views 10 | import Login from './Login'; 11 | import Update from './Update'; 12 | import Profile from './Profile'; 13 | 14 | export const appModeAtom = atom('update'); 15 | 16 | // `useNavigate` requires the component to already be inside a `Router`. 17 | // `MemoryRouter` is preferred over other routers because it doesn't conflict with 18 | // supabase's url auth mechanisms. 19 | export default function WrappedApp() { 20 | return 21 | 22 | 23 | } 24 | 25 | // email links will hit this route, which is opened in a browser; 26 | const isBrowser = window.electronAPI === undefined; 27 | 28 | function App() { 29 | const navigate = useNavigate(); 30 | const location = useLocation(); 31 | const [appMode, setAppMode] = useAtom(appModeAtom); 32 | 33 | useEffect(() => { 34 | posthog.init(Keys.posthog, { 35 | api_host: Urls.posthog, 36 | }); 37 | 38 | if (!isBrowser) { 39 | // will navigate back to '/' if app mode is not update 40 | navigate('/update'); 41 | 42 | window.electronAPI.getAppMode().then((mode) => { 43 | console.log('app mode received:', mode); 44 | setAppMode(mode); 45 | 46 | if (mode === 'update') { 47 | // should already be in /update 48 | 49 | // only start supabase checks if not in update mode 50 | return; 51 | } else { 52 | navigate('/'); 53 | } 54 | 55 | if (!supabase || !supabase.auth) return; 56 | 57 | const { 58 | data: { subscription } 59 | } = supabase.auth.onAuthStateChange((event, session) => { 60 | // probably not needed 61 | if (location.pathname === '/update') return; 62 | 63 | if (event === 'SIGNED_IN' && location.pathname === '/login') { 64 | console.log('login succeeded, navigating to /'); 65 | navigate('/'); 66 | } 67 | if (event === 'SIGNED_OUT' && location.pathname !== '/login') { 68 | console.log('logout succeeded, navigating to /login'); 69 | navigate('/login'); 70 | } 71 | 72 | if (session) { 73 | // hack: alias the previous anonymous user with the authorized user id 74 | const email = session.user.email; 75 | const name = session.user.user_metadata.name; 76 | 77 | const prev_posthog_id = posthog.get_distinct_id(); 78 | posthog.identify(session.user.id, { name, email }); 79 | posthog.alias(prev_posthog_id); 80 | } 81 | }); 82 | 83 | // does nothing here, but keep so we remember when cleaning 84 | return () => subscription.unsubscribe(); 85 | }); 86 | } 87 | }, []); 88 | 89 | if (isBrowser) { 90 | // while metavoice://magicLink isn't a valid redirect_url 91 | window.location.href = "metavoice://magicLink" + window.location.hash; 92 | 93 | return 94 |
95 |

Please open MetaVoice Live to continue

96 |

If nothing happens, try reloading the application with Ctrl+R

97 |
98 |
99 | } 100 | 101 | return 102 |
103 | 104 | } /> 105 | } /> 106 | } /> 107 | 108 | 109 |
110 |
111 | } 112 | 113 | function HelpLink() { 114 | return
115 | 116 | 117 | 118 | 119 | 120 |
121 | } -------------------------------------------------------------------------------- /services/desktop_app/src/styles.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --background: #232234; 3 | --modal: #181825; 4 | --modal-contrast: #262634; 5 | --low-contrast: #2a293c; 6 | --med-contrast: #303042; 7 | --high-contrast: #37364b; 8 | --highest-contrast: #504F66; 9 | --highlight: #ff3a27; 10 | --primary-text: #f7f7ff; 11 | --secondary-text: #8e8da2; 12 | } 13 | 14 | body { 15 | font-family: Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; 16 | font-size: 16px; 17 | -webkit-user-select: none; 18 | -webkit-app-region: drag; 19 | background-color: var(--background); 20 | color: var(--primary-text); 21 | } 22 | 23 | #root { 24 | height: 100vh; 25 | display: grid; 26 | } 27 | 28 | .App { 29 | align-self: top; 30 | justify-self: center; 31 | padding-top: 3rem; 32 | } 33 | 34 | .login-container { 35 | height: 330px; 36 | width: 330px; 37 | background-color: var(--low-contrast); 38 | text-align: center; 39 | padding: 34px 28px 8px 28px; 40 | margin-bottom: 27px; 41 | border-radius: 30px; 42 | } 43 | 44 | .preference-panel-content { 45 | background-color: var(--background); 46 | padding: 10px; 47 | } 48 | 49 | .text-description { 50 | color: var(--secondary-text); 51 | font-size: 14px; 52 | margin-top: -5px; 53 | margin-bottom: 10px; 54 | line-height: 1.3; 55 | } 56 | 57 | h1 { 58 | margin: 0; 59 | margin-bottom: 24px; 60 | padding-bottom: 18px; 61 | font-size: 24px; 62 | } 63 | 64 | input, 65 | button { 66 | padding: 9px; 67 | font-size: 16px; 68 | margin-bottom: 9px; 69 | } 70 | 71 | input, 72 | button, 73 | audio { 74 | /* Disables dragging for inputs to allow sliders & Windows clicks */ 75 | -webkit-app-region: no-drag; 76 | } 77 | 78 | button { 79 | width: 100%; 80 | } 81 | 82 | /* Conversion.js */ 83 | .conversion-container { 84 | min-width: 700px; 85 | } 86 | 87 | /* For some reason, mr-1 doesn't work */ 88 | .check-label { 89 | margin-right: 0.5rem; 90 | } 91 | 92 | .form-check-input:checked { 93 | background-color: var(--highlight) !important; 94 | border: 0; 95 | } 96 | 97 | .form-check-input:focus, 98 | .label::after, 99 | label.form-check-label:focus, 100 | .form-check-input::after, 101 | .form-check-input:not(:disabled):not(.disabled):active:focus { 102 | outline: 0; 103 | border: 0; 104 | box-shadow: 0 0 0 0.1rem var(--highlight) !important; 105 | } 106 | 107 | /*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/ 108 | .btn, 109 | .form-select { 110 | border-radius: 1000px; 111 | } 112 | 113 | .input-group-text { 114 | border-top-left-radius: 1000px !important; 115 | border-bottom-left-radius: 1000px !important; 116 | } 117 | 118 | .form-select, 119 | .form-select:focus, 120 | .input-group-text { 121 | color: var(--primary-text); 122 | background-color: var(--low-contrast) !important; 123 | border-color: var(--high-contrast); 124 | border-width: 1px; 125 | box-shadow: none; 126 | } 127 | 128 | .btn-secondary { 129 | background-color: var(--med-contrast); 130 | border-width: 0px; 131 | } 132 | 133 | .btn-secondary:hover, 134 | .btn-secondary:focus, 135 | .btn-secondary:active, 136 | .btn-secondary.active, 137 | .open>.dropdown-toggle.btn-secondary { 138 | background-color: var(--highest-contrast); 139 | box-shadow: none; 140 | } 141 | 142 | .btn-primary { 143 | background-color: var(--high-contrast) !important; 144 | border-color: var(--highlight); 145 | border-width: 0px; 146 | } 147 | 148 | .btn-primary:hover, 149 | .btn-primary:focus, 150 | .btn-primary:active, 151 | .btn-primary.active, 152 | .open>.dropdown-toggle.btn-primary { 153 | background-color: var(--highest-contrast) !important; 154 | box-shadow: none; 155 | } 156 | 157 | .btn-danger { 158 | background-color: var(--highlight); 159 | } 160 | 161 | .icon-wrapper { 162 | font-size: 2rem; 163 | } 164 | 165 | /* slow down the spinner animation */ 166 | .spinner-border { 167 | animation-duration: 1.2s; 168 | margin-right: 10px; 169 | } 170 | 171 | /* Loading.js */ 172 | .loading-overlay { 173 | display: none; 174 | background: #232234; 175 | align-items: center; 176 | justify-content: center; 177 | flex-direction: row; 178 | } 179 | 180 | .loading-overlay--fullscreen { 181 | position: fixed; 182 | bottom: 0; 183 | left: 0; 184 | right: 0; 185 | top: 0; 186 | z-index: 9998; 187 | } 188 | 189 | .loading-overlay.is-active { 190 | display: flex; 191 | } 192 | 193 | .loading-overlay p { 194 | margin-top: 0px; 195 | margin-bottom: 0px; 196 | font-size: 1.2rem; 197 | } 198 | 199 | /* founding member tag */ 200 | .founding-member { 201 | position: fixed; 202 | top: 1rem; 203 | right: 1rem; 204 | overflow: hidden; 205 | padding: 8px 10px; 206 | display: inline-block; 207 | margin: 25px 0 25px 25px; 208 | border-radius: 20px; 209 | text-decoration: none; 210 | text-align: center; 211 | font-size: 10px; 212 | font-family: sans-serif; 213 | background: var(--highlight); 214 | cursor: pointer; 215 | } 216 | 217 | .founding-member:hover { 218 | cursor: default; 219 | } 220 | 221 | .mv-accordion { 222 | margin-top: 3rem; 223 | max-width: 670px; 224 | } 225 | 226 | .accordion-item { 227 | background-color: var(--background); 228 | border-color: var(--high-contrast); 229 | } 230 | 231 | .accordion-header { 232 | color: white 233 | } 234 | 235 | .accordion-button { 236 | background-color: var(--background); 237 | color: white; 238 | } 239 | 240 | .accordion-button.collapsed::after { 241 | background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e"); 242 | } 243 | 244 | .accordion-button:not(.collapsed) { 245 | color: white; 246 | background-color: var(--low-contrast); 247 | } 248 | 249 | .accordion-button:not(.collapsed)::after { 250 | background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e"); 251 | transform: rotate(-180deg); 252 | color: white; 253 | background-color: var(--low-contrast); 254 | } 255 | 256 | .accordion-button::after { 257 | color: white; 258 | } 259 | 260 | .accordion-button:focus, 261 | .accordion-button:active { 262 | box-shadow: none; 263 | } 264 | 265 | .accordion-body { 266 | background-color: var(--background); 267 | color: white; 268 | padding: 10px 10px; 269 | } 270 | 271 | .session-feedback-modal { 272 | min-width: 520px; 273 | background-color: var(--background); 274 | } 275 | 276 | .send-feedback-button { 277 | margin-right: 10px; 278 | } 279 | 280 | .mv-error { 281 | color: var(--highlight); 282 | } 283 | 284 | figcaption { 285 | margin-bottom: 10px; 286 | } -------------------------------------------------------------------------------- /services/desktop_app/src/components/PreferencesModal.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useCallback, useEffect } from "react"; 2 | import { useNavigate } from "react-router-dom"; 3 | import Form from 'react-bootstrap/Form'; 4 | import Button from 'react-bootstrap/Button'; 5 | import Modal from 'react-bootstrap/Modal'; 6 | import OverlayTrigger from 'react-bootstrap/OverlayTrigger'; 7 | import Tooltip from 'react-bootstrap/Tooltip'; 8 | import { atom, useAtom } from "jotai"; 9 | import { SERVER_BASE_URL } from '../constants'; 10 | import { supabase } from "../supabase"; 11 | import posthog from 'posthog-js'; 12 | import './PreferencesModal.css' 13 | 14 | const getInitialSettings = () => { 15 | function createSetting(name, defaultValue, transform = (x) => x) { 16 | const raw = window.localStorage.getItem('setting:' + name); 17 | return { 18 | [name]: raw == null ? defaultValue : transform(raw) 19 | } 20 | } 21 | return { 22 | ...createSetting('noise-suppression-threshold', 5, Number), 23 | ...createSetting('callback-latency-ms', 400, Number), 24 | ...createSetting('targetSpeakerId', 'zeus', String), 25 | ...createSetting('inputDeviceId', -1, Number), 26 | ...createSetting('outputDeviceId', -1, Number), 27 | }; 28 | } 29 | 30 | // don't use this directly, it doesn't have persistence 31 | const _settingsAtomRaw = atom(getInitialSettings()); 32 | // this persists changes to localstorage, loaded back in by getInitialSettings 33 | export const settingsAtom = atom( 34 | (get) => get(_settingsAtomRaw), 35 | (get, set, newSettings) => { 36 | set(_settingsAtomRaw, newSettings) 37 | 38 | // save to localStorage 39 | Object.keys(newSettings).forEach((key) => { 40 | window.localStorage.setItem('setting:' + key, newSettings[key]); 41 | }); 42 | } 43 | ) 44 | 45 | export const appVersionAtom = atom('0.0.0'); 46 | 47 | export default function PreferencesModal() { 48 | const navigate = useNavigate(); 49 | const [show, setShow] = useState(false); 50 | const [settings, setSettings] = useAtom(settingsAtom); 51 | const [shareData, setShareData] = useState(true); 52 | 53 | const [appVersion, setAppVersion] = useAtom(appVersionAtom) 54 | 55 | useEffect(() => { 56 | const value = window.localStorage.getItem('MV_SHARE_DATA'); 57 | setShareData(value ? value === 'true' : true); 58 | 59 | window.electronAPI.getAppVersion().then((version) => { 60 | setAppVersion(version); 61 | }); 62 | }, []) 63 | 64 | const handleSettingChange = async (event) => { 65 | const settingName = event.target.name; 66 | const value = event.target.value; 67 | 68 | try { 69 | posthog.capture(`user requested ${settingName} change`, { value }); 70 | await fetch(`${SERVER_BASE_URL}/${settingName}?value=${value}`, { method: 'GET' }); 71 | posthog.capture(`user requested ${settingName} change succeeded`, { value }) 72 | } catch (error) { 73 | posthog.capture(`user requested ${settingName} change failed`, { value, error }) 74 | console.log(`GET /${settingName} failed with error: ${error}`) 75 | } 76 | 77 | setSettings({ 78 | ...settings, 79 | [settingName]: value 80 | }); 81 | } 82 | 83 | const handleSwitchOnChange = async (event) => { 84 | const value = event.target.checked; 85 | try { 86 | await fetch(`${SERVER_BASE_URL}/data-share?value=${value}`, { method: 'GET' }); 87 | window.localStorage.setItem('MV_SHARE_DATA', value); 88 | } catch (error) { 89 | console.log(`GET /data-share failed with error: ${error}`) 90 | } 91 | 92 | setShareData(value); 93 | } 94 | 95 | const handleClose = () => setShow(false); 96 | const handleShow = () => setShow(true); 97 | 98 | const logout = useCallback(() => { 99 | supabase.auth.signOut().then(() => { 100 | posthog.reset(); 101 | navigate("/login"); 102 | }); 103 | }, [navigate]); 104 | 105 | // useful for debugging, and getting users unstuck 106 | window.logout = logout; 107 | 108 | return
109 | 112 | 113 | 114 | Advanced Settings 115 | 116 | 117 |
118 | Noise Supression: {Number(settings['noise-suppression-threshold'] || 0).toFixed(1)} 119 |
120 | min 121 | 130 | max 131 |
132 |
133 | 134 |
135 | {/* this parameter is half the experienced latency, so is doubled in slider */} 136 | Latency: {Number(settings['callback-latency-ms']) * 2}ms 137 |
138 | min 139 | 148 | max 149 |
150 |
151 | 152 |
153 | 160 | 164 | By clicking send, you agree to share your data with MetaVoice striclty for the purposes of providing you a better voice & app experience. 165 | 166 | } 167 | > 168 | 169 | 170 | 171 |
172 | 173 | 174 |
175 |
176 | 177 |
178 |
179 |

{ navigate('/update') }} 182 | >Version: {appVersion}

183 |
184 | 185 | 188 | 189 |
190 |
191 | } 192 | -------------------------------------------------------------------------------- /services/desktop_app/util.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const fs = require('fs'); 3 | const crypto = require('crypto'); 4 | 5 | const unzipper = require('unzipper'); 6 | const request = require("request"); 7 | const { app, Notification } = require('electron'); 8 | const si = require('systeminformation'); 9 | 10 | function deferPromise() { 11 | const bag = {}; 12 | return Object.assign(new Promise((resolve, reject) => { 13 | bag.resolve = resolve; 14 | bag.reject = reject; 15 | }), bag); 16 | } 17 | 18 | function checkNeedsNewVersion(mlVersion) { 19 | const currentMlVersionPath = path.resolve(`${__dirname}/dist/metavoice/version.txt`); 20 | const unzipFinishedCheck = path.resolve(`${__dirname}/dist/.unzip-finished`); 21 | let currentVersion = 'none' 22 | try { 23 | currentVersion = fs.readFileSync(currentMlVersionPath, 'utf-8'); 24 | 25 | if (!fs.existsSync(unzipFinishedCheck)) { 26 | // unzip did not complete 27 | return { needsNewVersion: true, reason: 'unzip did not finish' }; 28 | } 29 | 30 | if (currentVersion === 'local') { 31 | return { needsNewVersion: false, reason: 'local version' }; 32 | } 33 | // current major, minor, patch 34 | const [cM, cm, cp] = currentVersion.split('.').map(Number); 35 | // requested major, minor, patch 36 | const [rM, rm, rp] = mlVersion.split('.').map(Number); 37 | 38 | // major: upgrade or downgrade 39 | // minor: upgrade only 40 | // patch: upgrade only 41 | return { 42 | needsNewVersion: cM !== rM || cm < rm || (cm === rm && cp < rp), 43 | reason: `current version ${currentVersion} is not compatible with requested version ${mlVersion}` 44 | }; 45 | } catch (e) { 46 | // if no version file exists or wasn't parseable, force upgrade. 47 | return { 48 | needsNewVersion: true, 49 | reason: 'no valid mvml installation detected' 50 | }; 51 | } 52 | } 53 | 54 | // check whether port is available for use, if not, increment by 1 and try again. 55 | function findFreePort(port) { 56 | return new Promise((resolve, reject) => { 57 | const server = require('http').createServer(); 58 | server.on('error', reject); 59 | server.listen(port, () => { 60 | server.close(() => { 61 | resolve(port); 62 | }); 63 | }); 64 | }).catch(() => { 65 | return findFreePort(port + 1); 66 | }); 67 | } 68 | 69 | function notify({ title, body }) { 70 | if (app.isReady()) { 71 | new Notification({ 72 | title, 73 | body, 74 | }).show(); 75 | } else { 76 | app.on('ready', () => { 77 | new Notification({ 78 | title, 79 | body, 80 | }).show(); 81 | }); 82 | } 83 | } 84 | 85 | // right now we only officially support windows with intel cpu and nvidia gpu 86 | async function warnOnUnsupportedPlatform() { 87 | let warned = false; 88 | const warnBadPlatform = (reason) => { 89 | if (warned) return; 90 | warned = true; 91 | 92 | notify({ 93 | title: 'Unsupported Platform', 94 | body: `MetaVoice currently only officially supports Windows 10+ with an Intel CPU and Nvidia GPU. ${reason}. Some features may still work.`, 95 | }); 96 | } 97 | 98 | if (process.platform !== 'win32') { 99 | warnBadPlatform('You are not on Windows') 100 | return; 101 | } 102 | 103 | if (process.arch !== 'x64') { 104 | warnBadPlatform('You are not on a 64-bit machine') 105 | return; 106 | } 107 | 108 | si.graphics().then(data => { 109 | if (!data.controllers.some(c => c.vendor.includes('NVIDIA'))) { 110 | warnBadPlatform('Your GPU is not Nvidia') 111 | } 112 | }); 113 | 114 | si.cpu().then(data => { 115 | if (!data.manufacturer.includes('Intel')) { 116 | warnBadPlatform('Your CPU is not Intel') 117 | } 118 | }); 119 | } 120 | 121 | async function updateMvml(opts) { 122 | const { 123 | mlVersion, 124 | mlServer, 125 | log, 126 | logError, 127 | retriesLeft, 128 | } = opts; 129 | 130 | if (retriesLeft <= 0) { 131 | logError('mvml update: retried too many times, aborting. Please contact gm@themetavoice.xyz for help'); 132 | return; 133 | } 134 | 135 | try { 136 | const pkgName = `mvml-${process.platform}-${mlVersion}.zip` 137 | const downloadDestination = path.resolve(`${app.getPath('downloads')}/${pkgName}`) 138 | const destination = path.resolve(`${__dirname}/dist`); 139 | 140 | // delete previous installation if present 141 | if (fs.existsSync(destination)) { 142 | fs.rmSync(destination, { recursive: true }); 143 | } 144 | 145 | const alreadyDownloadedVersion = fs.existsSync(downloadDestination); 146 | 147 | if (!alreadyDownloadedVersion) { 148 | const fileStream = fs.createWriteStream(downloadDestination, { flags: 'wx' }); 149 | 150 | log(`mvml update: model not found locally, downloading ml model ${pkgName}...`); 151 | 152 | try { 153 | await new Promise((resolve, reject) => { 154 | const url = new URL(mlServer + '/' + pkgName); 155 | // node-fetch and axios both created dependency issues, so using native modules instead. 156 | const pipe = request(mlServer + '/' + pkgName) 157 | .pipe(fileStream); 158 | pipe.on('finish', resolve); 159 | pipe.on('error', reject); 160 | }); 161 | } catch (err) { 162 | if (err.res && err.res.statusCode === 403) { 163 | // file is not existing/accessible 164 | logError('mvml update: ml model not found on server (403 response)', err); 165 | } 166 | 167 | // delete the mvml file 168 | fs.rmSync(downloadDestination); 169 | throw err; 170 | } 171 | } else { 172 | log('mvml update: ml model already downloaded, skipping download') 173 | } 174 | 175 | log('mvml update: ml model downloaded, checking integrity ...'); 176 | try { 177 | // get checksum of stored file, and compare to checksum of file on server 178 | const checksum = await new Promise((resolve, reject) => { 179 | const hash = crypto.createHash('sha256'); 180 | const stream = fs.createReadStream(downloadDestination); 181 | stream.on('error', reject); 182 | stream.on('data', chunk => hash.update(chunk)); 183 | stream.on('end', () => resolve(hash.digest('hex'))); 184 | }); 185 | log(`mvml update: ml model checksum from local zip file calculated as ${checksum}`); 186 | 187 | log(`mvml update: downloading expected checksum from server ...`); 188 | const checksumResponse = await fetch(`${mlServer}/${pkgName}.sha256`); 189 | const checksumText = await checksumResponse.text(); 190 | const checksumServer = checksumText.trim().split(' ')[0]; 191 | 192 | if (checksum !== checksumServer) { 193 | logError(`mvml update: checksum mismatch, expected ${checksumServer}, got ${checksum}`); 194 | log(`mvml update: deleting downloaded ml model to try download again ...`); 195 | fs.rmSync(downloadDestination); 196 | throw new Error(`checksum mismatch, expected ${checksumServer}, got ${checksum}`); 197 | } else { 198 | log(`mvml update: ml model checksum from server matches local checksum, continuing ...`) 199 | } 200 | } catch (err) { 201 | logError('mvml update: fatal error checking integrity of the ml model', err); 202 | throw err; 203 | } 204 | 205 | log('mvml update: ml model stored, unzipping ...'); 206 | try { 207 | // could pipe in directly from fetch, but this makes debugging easier, allows caching, and better progress updates for user 208 | const stream = fs.createReadStream(downloadDestination).pipe(unzipper.Extract({ path: destination })); 209 | await new Promise((resolve, reject) => { 210 | stream.on('finish', resolve); 211 | stream.on('error', reject); 212 | }); 213 | 214 | // create file to indicate the unzipping has definitely finished 215 | fs.writeFileSync(path.resolve(`${destination}/.unzip-finished`), 'true'); 216 | } catch (err) { 217 | logError('mvml update: fatal error unzipping the ml model', err); 218 | throw err; 219 | } 220 | 221 | log('mvml update: ml model unzipped, validating result ...'); 222 | 223 | const { needsNewVersion, reason } = checkNeedsNewVersion(mlVersion); 224 | 225 | if (needsNewVersion) { 226 | throw new Error(`installation not valid: ${reason}`); 227 | } 228 | 229 | log('mvml update: success! Restarting the app in 5 seconds. If it doesn\'t restart, please let us know and try to restart it manually.') 230 | 231 | setTimeout(() => { 232 | app.relaunch(); 233 | app.exit(); 234 | }, 5000); 235 | } catch (err) { 236 | logError('mvml update: fatal error updating the ml model, please report this to gm@themetavoice.xyz', err); 237 | log(`mvml update: will now attempt to update again (${retriesLeft} left)`); 238 | log(`mvml update: =====================================================================================`); 239 | updateMvml({ 240 | ...opts, 241 | retriesLeft: retriesLeft - 1, 242 | }) 243 | } 244 | } 245 | 246 | module.exports = { 247 | deferPromise, 248 | checkNeedsNewVersion, 249 | updateMvml, 250 | findFreePort, 251 | notify, 252 | warnOnUnsupportedPlatform 253 | } -------------------------------------------------------------------------------- /services/desktop_app/server/main.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import asyncio 3 | import multiprocessing 4 | import multiprocessing as mp 5 | import os 6 | import time 7 | from dataclasses import dataclass 8 | from multiprocessing import Process, Value 9 | from typing import Optional 10 | 11 | import numpy as np 12 | 13 | # librosa uses the deprecated alias 14 | np.complex = complex 15 | 16 | import librosa 17 | import sounddevice as sd 18 | import soundfile as sf 19 | import urllib3 20 | import uvicorn 21 | 22 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 23 | 24 | import sys 25 | 26 | from data_types import DeviceMap 27 | from fastapi import FastAPI, HTTPException, WebSocket 28 | from fastapi.middleware.cors import CORSMiddleware 29 | from fastapi.responses import StreamingResponse 30 | from portaudio_utils import get_devices 31 | 32 | # TODO is this safe? ai wasn't found otherwise, but depending on how this file is loaded, 33 | # it might allow third parties to overwrite # more modules and maybe that's not a big deal 34 | # as they can override the files directly anyway? 35 | sys.path.append('../..') 36 | 37 | from ai.spectrogram_conversion.data_types import InferencePipelineMode 38 | from ai.spectrogram_conversion.inference_rt import run_inference_rt 39 | from ai.spectrogram_conversion.params import num_mels, num_samples, sample_rate 40 | from ai.spectrogram_conversion.timedscope import TimedScope, get_logger 41 | from ai.spectrogram_conversion.utils.utils import get_conversion_root 42 | from common.aws_utils import upload_directory_to_s3 43 | 44 | _LOGGER = get_logger(__name__) 45 | IS_MOCK = os.environ.get("IS_MOCK", "false") == "true" 46 | 47 | 48 | @dataclass 49 | class UserState: 50 | email: str = "" 51 | issuer: str = "" 52 | should_capture_data: bool = True 53 | 54 | 55 | USER_STATE = UserState() 56 | convert_process: Optional[Process] = None 57 | stop_pipeline: Optional[Value] = None 58 | has_pipeline_started: Optional[Value] = None 59 | # TODO sidroopdaska: swap this for application hooks 60 | # TODO sidroopdaska: use mp.Manager.dict 61 | noise_suppression_threshold: Optional[Value] = None 62 | callback_latency_ms: Optional[Value] = None 63 | latency_queue: Optional[multiprocessing.Queue] = None 64 | frame_dropping: Optional[multiprocessing.Queue] = None 65 | 66 | 67 | def sigterm_handler(): 68 | global convert_process 69 | if not convert_process: 70 | return 71 | 72 | convert_process.terminate() 73 | 74 | 75 | def convert_process_target( 76 | stop_pipeline: Value, 77 | has_pipeline_started: Value, 78 | input_device_idx: int, 79 | output_device_idx: int, 80 | noise_suppression_threshold: Value, 81 | callback_latency_ms: Value, 82 | target_speaker: str, 83 | session_upload_path: str, 84 | latency_queue: multiprocessing.Queue, 85 | frame_dropping: multiprocessing.Queue, 86 | ): 87 | # TODO sidroopdaska: replace argparse.Namespace with dataclass 88 | # TODO sidroopdaska: lazy loading of model 89 | opt = argparse.Namespace( 90 | mode=InferencePipelineMode.online_crossfade, 91 | input_device_idx=input_device_idx, 92 | output_device_idx=output_device_idx, 93 | noise_suppression_threshold=noise_suppression_threshold, 94 | callback_latency_ms=callback_latency_ms, 95 | session_upload_path=session_upload_path, 96 | target_speaker=target_speaker, 97 | ) 98 | 99 | run_inference_rt( 100 | opt, 101 | stop_pipeline=stop_pipeline, 102 | has_pipeline_started=has_pipeline_started, 103 | latency_queue=latency_queue, 104 | frame_dropping=frame_dropping, 105 | ) 106 | 107 | 108 | ######## 109 | # FastAPI 110 | ######## 111 | app = FastAPI() 112 | app.add_middleware(CORSMiddleware, allow_origins=["*"]) 113 | 114 | 115 | @app.get("/is-alive") 116 | def get_is_alive(): 117 | return True 118 | 119 | 120 | @app.get("/device-map") 121 | def get_device_map(mode: str = "all") -> DeviceMap: 122 | return get_devices(mode) 123 | 124 | 125 | @app.get("/register-user") 126 | def register_user(email: str, issuer: str, share_data: bool, noise_suppression: float, callback_latency_ms_: int): 127 | global USER_STATE, noise_suppression_threshold, callback_latency_ms 128 | USER_STATE.email = email 129 | USER_STATE.issuer = issuer 130 | USER_STATE.should_capture_data = share_data 131 | 132 | # double 133 | noise_suppression_threshold = Value("d", noise_suppression) 134 | # unsigned int 135 | callback_latency_ms = Value("I", callback_latency_ms_) 136 | print(share_data) 137 | print(type(share_data)) 138 | print(type(noise_suppression)) 139 | print(noise_suppression_threshold.value) 140 | print(callback_latency_ms.value) 141 | return True 142 | 143 | 144 | @app.get("/start-convert") 145 | def get_start_convert(input_device_idx: int, output_device_idx: int, app_version: str, target_speaker: str): 146 | # not a true session id, but avoids conflicts 147 | session_id = time.time() 148 | 149 | if IS_MOCK: 150 | time.sleep(1) 151 | return True 152 | 153 | with TimedScope("get_start_convert", _LOGGER): 154 | global convert_process, stop_pipeline, has_pipeline_started, noise_suppression_threshold, callback_latency_ms, latency_queue, frame_dropping 155 | 156 | stop_pipeline = Value("i", 0) 157 | has_pipeline_started = Value("i", 0) 158 | latency_queue = multiprocessing.Queue() 159 | frame_dropping = multiprocessing.Queue() 160 | convert_process = Process( 161 | target=convert_process_target, 162 | args=( 163 | stop_pipeline, 164 | has_pipeline_started, 165 | input_device_idx, 166 | output_device_idx, 167 | noise_suppression_threshold, 168 | callback_latency_ms, 169 | target_speaker, 170 | (f"{USER_STATE.email}/{session_id}" if USER_STATE.should_capture_data else None), 171 | latency_queue, 172 | frame_dropping, 173 | ), 174 | ) 175 | convert_process.start() 176 | 177 | while not has_pipeline_started.value: 178 | time.sleep(0.2) 179 | return True 180 | 181 | 182 | @app.websocket_route("/ws-frame-health") 183 | async def get_latency(websocket: WebSocket): 184 | await websocket.accept() 185 | 186 | global frame_dropping 187 | 188 | while True: 189 | if frame_dropping: 190 | frame_drops = [] 191 | 192 | while not frame_dropping.empty(): 193 | frame_drops.append(frame_dropping.get_nowait()) 194 | 195 | if len(frame_drops) > 0: 196 | await websocket.send_json(frame_drops) 197 | else: 198 | await asyncio.sleep(1) 199 | else: 200 | await asyncio.sleep(1) 201 | 202 | 203 | # TODO sidroopdaska: use correct HTTP verbs. Using GET right now since its easy to test from the browser 204 | @app.get("/stop-convert") 205 | def get_stop_convert(): 206 | if IS_MOCK: 207 | time.sleep(1) 208 | return True 209 | 210 | with TimedScope("get_stop_convert", _LOGGER): 211 | global convert_process, stop_pipeline, latency_queue 212 | if not convert_process: 213 | return True 214 | 215 | latency_records = [] 216 | while not latency_queue.empty(): 217 | latency_records.append(latency_queue.get_nowait()) 218 | if len(latency_records) > 30: 219 | latency_records = latency_records[-30:] 220 | latency_records 221 | 222 | with stop_pipeline.get_lock(): 223 | stop_pipeline.value = 1 224 | 225 | convert_process.join(5) 226 | if convert_process.is_alive(): 227 | convert_process.terminate() 228 | 229 | return {"latency_records": latency_records} 230 | 231 | 232 | # TODO sidroopdaska: convert to POST or setup a websocket to make more generalisable 233 | @app.get("/noise-suppression-threshold") 234 | def get_noise_suppression_threshold(value: float): 235 | global noise_suppression_threshold 236 | 237 | with noise_suppression_threshold.get_lock(): 238 | noise_suppression_threshold.value = value 239 | return True 240 | 241 | 242 | @app.get("/callback-latency-ms") 243 | def get_callback_latency_ms(value: int): 244 | global callback_latency_ms 245 | 246 | with callback_latency_ms.get_lock(): 247 | callback_latency_ms.value = value 248 | return True 249 | 250 | 251 | @app.get("/data-share") 252 | def get_data_share(value: bool): 253 | global USER_STATE 254 | USER_STATE.should_capture_data = value 255 | return True 256 | 257 | 258 | @app.get("/audio") 259 | def get_audio(audio_type: str): 260 | if audio_type not in ["original", "converted"]: 261 | return HTTPException(status_code=400, detail="Bad request. Wrong `audio_type` requested") 262 | 263 | fname = os.path.join(get_conversion_root(), f"{audio_type}.wav") 264 | if not os.path.exists(fname): 265 | return HTTPException(status_code=404, detail=f"Audio {audio_type}.wav does not exist") 266 | 267 | return StreamingResponse(content=open(fname, "rb"), media_type="audio/wav") 268 | 269 | 270 | # TODO sidroopdaska: POST results in CORS and doesn't work with the react development server 271 | @app.get("/feedback") 272 | def get_feedback(content: str, duration: int): 273 | global USER_STATE 274 | 275 | # write content to disk 276 | if content: 277 | with open(f"{get_conversion_root()}/content.txt", "w") as f: 278 | f.write(content) 279 | 280 | # trim audio length 281 | for f in ["original.wav", "converted.wav"]: 282 | fname = os.path.join(get_conversion_root(), f) 283 | wav, sr = librosa.load(fname) 284 | if len(wav) < duration * sample_rate: 285 | continue 286 | wav = wav[-(duration * sample_rate) :] 287 | sf.write(fname, wav, sample_rate) 288 | 289 | # not a true session id, but avoids conflicts 290 | session_id = time.time() 291 | 292 | # upload to cloud 293 | upload_directory_to_s3( 294 | get_conversion_root(), 295 | object_prefix=f"{USER_STATE.email}/{session_id}", 296 | ) 297 | 298 | 299 | @app.on_event("shutdown") 300 | def shutdown_event(): 301 | sigterm_handler() 302 | 303 | 304 | if __name__ == "__main__": 305 | # required to enable multiprocessing for a bundled application 306 | multiprocessing.freeze_support() 307 | 308 | # start server 309 | uvicorn.run(app, host="127.0.0.1", port=58000, log_level="info") 310 | -------------------------------------------------------------------------------- /ai/spectrogram_conversion/inference_rt.py: -------------------------------------------------------------------------------- 1 | """ 2 | python inference_rt.py --trg_id 1 --mode online_crossfade 3 | DEBUG=inference_rt python inference_rt.py --trg_id 1 --mode online_crossfade 4 | """ 5 | import argparse 6 | import math 7 | import multiprocessing 8 | import os 9 | import time 10 | from collections import deque 11 | from multiprocessing import Process, Queue, Value 12 | from queue import Empty 13 | from typing import Callable, Optional 14 | 15 | import numpy as np 16 | import pyaudio 17 | 18 | from ai.common.torch_utils import get_device, set_seed 19 | from ai.spectrogram_conversion.data_types import InferencePipelineMode 20 | from ai.spectrogram_conversion.params import (MAX_INFER_SAMPLES_VC, SEED, 21 | sample_rate) 22 | from ai.spectrogram_conversion.perf_counter import DebugPerfCounter 23 | from ai.spectrogram_conversion.timedscope import TimedScope, get_logger 24 | from ai.spectrogram_conversion.utils.audio_utils import get_audio_io_indices 25 | from ai.spectrogram_conversion.utils.multiprocessing_utils import SharedCounter 26 | from ai.spectrogram_conversion.utils.utils import ( 27 | get_conversion_root, get_ordered_data_from_circular_buffer) 28 | from ai.spectrogram_conversion.voice_conversion import ModelConversionPipeline 29 | 30 | _LOGGER = get_logger(os.path.basename(__file__)) 31 | set_seed(SEED) 32 | 33 | # ---------------- 34 | # PyAudio Setup 35 | # ---------------- 36 | 37 | p = pyaudio.PyAudio() 38 | FORMAT = pyaudio.paFloat32 39 | CHANNELS = 1 40 | RATE = sample_rate 41 | 42 | # serves as the head pointer for the audio_in & audio_out circular buffers 43 | PACKET_ID = 0 44 | BUFFER_OVERFLOW = False 45 | PACKET_START_S = None 46 | WAV: Optional[np.ndarray] = None 47 | 48 | 49 | # TODO sidroopdaska: remove numpy.ndarray allocation 50 | # TODO sidroopdaska: create a lock-free, single producer and single consumer ring buffer 51 | def get_io_stream_callback( 52 | q_in: Queue, 53 | q_in_counter: Value, 54 | data: list, 55 | audio_in: list, 56 | q_out: Queue, 57 | q_out_counter: Value, 58 | audio_out: list, 59 | MAX_RECORD_SEGMENTS: int, 60 | latency_queue: Optional[multiprocessing.Queue] = None, 61 | frame_dropping: Optional[multiprocessing.Queue] = None, 62 | ) -> Callable: 63 | def callback(in_data, frame_count, time_info, status): 64 | global PACKET_ID, PACKET_START_S, WAV, BUFFER_OVERFLOW 65 | 66 | _LOGGER.debug(f"io_stream_callback duration={time.time() - PACKET_START_S}") 67 | _LOGGER.debug(f"io_stream_callback frame_count={frame_count}") 68 | if status: 69 | _LOGGER.warn(f"status: {status}") 70 | 71 | in_data_np = np.frombuffer(in_data, dtype=np.float32) 72 | 73 | audio_in[PACKET_ID] = in_data_np 74 | data.append(in_data_np) 75 | q_in.put_nowait( 76 | ( 77 | PACKET_ID, 78 | PACKET_START_S, 79 | # passing data as bytes in multiprocessing:Queue is quicker 80 | np.array(data).flatten().astype(np.float32)[-MAX_INFER_SAMPLES_VC:].tobytes(), 81 | ) 82 | ) 83 | q_in_counter.increment() 84 | 85 | # prepare output 86 | out_data = None 87 | p_id, p_start_s = None, None 88 | latency_dump = None 89 | 90 | if q_out_counter.value == 0: 91 | _LOGGER.info("q_out: underflow") 92 | out_data = np.zeros(frame_count).astype(np.float32).tobytes() 93 | 94 | if frame_dropping: 95 | frame_dropping.put_nowait(-1) 96 | if latency_queue: 97 | latency_dump = 1000 98 | elif q_out_counter.value == 1: 99 | p_id, p_start_s, out_data = q_out.get_nowait() 100 | q_out_counter.increment(-1) 101 | 102 | if frame_dropping: 103 | frame_dropping.put_nowait(0) 104 | if latency_queue: 105 | latency_dump = time.time() - p_start_s 106 | else: 107 | _LOGGER.info("q_out: overflow") 108 | 109 | if frame_dropping: 110 | frame_dropping.put_nowait(1) 111 | if latency_queue: 112 | latency_dump = 0 113 | 114 | while not q_out.empty(): 115 | try: 116 | p_id, p_start_s, out_data = q_out.get_nowait() 117 | q_out_counter.increment(-1) 118 | except Empty: 119 | pass 120 | 121 | if latency_queue: 122 | latency_queue.put_nowait(latency_dump) 123 | 124 | if p_id and p_id % 3 == 0: 125 | _LOGGER.info(f"roundtrip: {time.time() - p_start_s}") 126 | 127 | audio_out[PACKET_ID] = np.frombuffer(out_data, dtype=np.float32) 128 | 129 | # update vars 130 | if (PACKET_ID + 1) >= MAX_RECORD_SEGMENTS: 131 | PACKET_ID = 0 132 | BUFFER_OVERFLOW = True 133 | else: 134 | PACKET_ID += 1 135 | 136 | PACKET_START_S = time.time() 137 | return (out_data, pyaudio.paContinue) 138 | 139 | return callback 140 | 141 | 142 | # -------------------- 143 | # Conversion pipeline 144 | # -------------------- 145 | class ConversionPipeline(ModelConversionPipeline): 146 | def __init__(self, opt: argparse.Namespace): 147 | super().__init__(opt) 148 | 149 | fade_duration_ms = 20 150 | self._fade_samples = int(fade_duration_ms / 1000 * sample_rate) # 20ms 151 | 152 | self._linear_fade_in = np.linspace(0, 1, self._fade_samples, dtype=np.float32) 153 | self._linear_fade_out = np.linspace(1, 0, self._fade_samples, dtype=np.float32) 154 | self._old_samples = np.zeros(self._fade_samples, dtype=np.float32) 155 | 156 | def run(self, wav: np.ndarray, HDW_FRAMES_PER_BUFFER: int): 157 | if self._opt.mode == InferencePipelineMode.online_crossfade: 158 | return self.run_cross_fade(wav, HDW_FRAMES_PER_BUFFER) 159 | elif self._opt.mode == InferencePipelineMode.online_with_past_future: 160 | raise NotImplementedError 161 | else: 162 | raise Exception(f"Mode: {self._opt.mode} unsupported") 163 | 164 | # Linear cross-fade 165 | def run_cross_fade(self, wav: np.ndarray, HDW_FRAMES_PER_BUFFER: int): 166 | with DebugPerfCounter("voice_conversion", _LOGGER): 167 | with DebugPerfCounter("model", _LOGGER): 168 | out = self.infer(wav) 169 | 170 | # suppress output if excessive model amplification detected 171 | threshold = None 172 | if type(self._opt.noise_suppression_threshold) == float: 173 | threshold = self._opt.noise_suppression_threshold 174 | else: 175 | with self._opt.noise_suppression_threshold.get_lock(): 176 | threshold = self._opt.noise_suppression_threshold.value 177 | 178 | _LOGGER.debug(f"noise_suppression_threshold: {threshold}") 179 | if np.max(np.abs(out)) > (threshold * np.max(np.abs(wav))): 180 | _LOGGER.debug("supressing noise") 181 | out = 0 * out 182 | 183 | # cross-fade = fade_in + fade_out 184 | out[-(HDW_FRAMES_PER_BUFFER + self._fade_samples) : -HDW_FRAMES_PER_BUFFER] = ( 185 | out[-(HDW_FRAMES_PER_BUFFER + self._fade_samples) : -HDW_FRAMES_PER_BUFFER] * self._linear_fade_in 186 | ) + (self._old_samples * self._linear_fade_out) 187 | # save 188 | self._old_samples = out[-self._fade_samples :] 189 | # send 190 | out = out[-(HDW_FRAMES_PER_BUFFER + self._fade_samples) : -self._fade_samples] 191 | return out 192 | 193 | 194 | # ------------------- 195 | # Main app processes 196 | # ------------------- 197 | def conversion_process_target( 198 | stop: Value, 199 | q_in: Queue, 200 | q_out: Queue, 201 | q_in_counter: SharedCounter, 202 | q_out_counter: SharedCounter, 203 | model_warmup_complete: Value, 204 | opt: dict, 205 | HDW_FRAMES_PER_BUFFER: int, 206 | ): 207 | voice_conversion = ConversionPipeline(opt) 208 | 209 | # warmup models into the cache 210 | warmup_iterations = 10 211 | for _ in range(warmup_iterations): 212 | wav = np.random.rand(MAX_INFER_SAMPLES_VC).astype(np.float32) 213 | voice_conversion.run(wav, HDW_FRAMES_PER_BUFFER) 214 | model_warmup_complete.value = 1 215 | 216 | try: 217 | while not stop.value: 218 | p_id, p_start_s, wav_bytes = q_in.get() 219 | q_in_counter.increment(-1) 220 | 221 | wav = np.frombuffer(wav_bytes, dtype=np.float32) 222 | out = voice_conversion.run(wav, HDW_FRAMES_PER_BUFFER) 223 | 224 | q_out.put_nowait((p_id, p_start_s, out.tobytes())) 225 | q_out_counter.increment() 226 | except KeyboardInterrupt: 227 | pass 228 | finally: 229 | _LOGGER.info("conversion_process_target: stopped") 230 | 231 | 232 | def run_inference_rt( 233 | opt: argparse.Namespace, 234 | stop_pipeline: Value, 235 | has_pipeline_started: Optional[Value] = None, 236 | latency_queue: Optional[multiprocessing.Queue] = None, 237 | frame_dropping: Optional[multiprocessing.Queue] = None, 238 | ): 239 | """ 240 | NOTE: make sure to call 'multiprocessing.freeze_support()' from the __main__ 241 | prior to invoking this function in a frozen application 242 | """ 243 | global PACKET_START_S, WAV 244 | 245 | HDW_FRAMES_PER_BUFFER = math.ceil(sample_rate * opt.callback_latency_ms.value / 1000) 246 | NUM_CHUNKS = math.ceil(MAX_INFER_SAMPLES_VC / HDW_FRAMES_PER_BUFFER) 247 | MAX_RECORD_SEGMENTS = 5 * 60 * sample_rate // HDW_FRAMES_PER_BUFFER # 5 mins in duration 248 | # make sure dependencies are updated before starting the pipeline 249 | _LOGGER.debug(f"MAX_RECORD_SEGMENTS: {MAX_RECORD_SEGMENTS}") 250 | _LOGGER.debug(f"HDW_FRAMES_PER_BUFFER: {HDW_FRAMES_PER_BUFFER}") 251 | _LOGGER.debug(f"NUM_CHUNKS: {NUM_CHUNKS}") 252 | 253 | # init 254 | audio_in = np.zeros((MAX_RECORD_SEGMENTS, HDW_FRAMES_PER_BUFFER), dtype=np.float32) 255 | audio_out = np.zeros((MAX_RECORD_SEGMENTS, HDW_FRAMES_PER_BUFFER), dtype=np.float32) 256 | 257 | stop_process = Value("i", 0) 258 | model_warmup_complete = Value("i", 0) 259 | q_in, q_out = Queue(), Queue() # TODO sidroopdaska: create wrapper class for multiprocessing:Queue & shared counter 260 | q_in_counter, q_out_counter = SharedCounter(0), SharedCounter(0) 261 | 262 | # create directory for recordings 263 | conversion_root = get_conversion_root() 264 | os.makedirs(conversion_root, exist_ok=True) 265 | 266 | # create rolling deque for io_stream data packets 267 | data = deque(maxlen=NUM_CHUNKS) 268 | for _ in range(NUM_CHUNKS): 269 | in_data = np.zeros(HDW_FRAMES_PER_BUFFER, dtype=np.float32) 270 | data.append(in_data) 271 | 272 | # run pipeline 273 | try: 274 | _LOGGER.info(f"backend={get_device()}") 275 | _LOGGER.info(f"opt={opt}") 276 | 277 | conversion_process = Process( 278 | target=conversion_process_target, 279 | args=( 280 | stop_process, 281 | q_in, 282 | q_out, 283 | q_in_counter, 284 | q_out_counter, 285 | model_warmup_complete, 286 | opt, 287 | HDW_FRAMES_PER_BUFFER, 288 | ), 289 | ) 290 | conversion_process.start() 291 | 292 | with TimedScope("model_warmup", _LOGGER): 293 | while not model_warmup_complete.value: 294 | time.sleep(1) 295 | 296 | io_stream = p.open( 297 | format=FORMAT, 298 | channels=CHANNELS, 299 | rate=RATE, 300 | input=True, 301 | output=True, 302 | start=False, 303 | frames_per_buffer=HDW_FRAMES_PER_BUFFER, 304 | input_device_index=opt.input_device_idx, 305 | output_device_index=opt.output_device_idx, 306 | stream_callback=get_io_stream_callback( 307 | q_in, 308 | q_in_counter, 309 | data, 310 | audio_in, 311 | q_out, 312 | q_out_counter, 313 | audio_out, 314 | MAX_RECORD_SEGMENTS, 315 | latency_queue, 316 | frame_dropping, 317 | ), 318 | ) 319 | io_stream.start_stream() 320 | PACKET_START_S = time.time() 321 | 322 | # hook for calling process 323 | if has_pipeline_started is not None: 324 | with has_pipeline_started.get_lock(): 325 | has_pipeline_started.value = 1 326 | 327 | while not stop_pipeline.value: 328 | time.sleep(0.2) 329 | 330 | finally: 331 | with stop_process.get_lock(): 332 | stop_process.value = 1 333 | conversion_process.join() 334 | 335 | if io_stream: 336 | io_stream.close() 337 | p.terminate() 338 | 339 | # empty out the queues prior to deletion 340 | while not q_in.empty(): 341 | try: 342 | q_in.get_nowait() 343 | except Empty: 344 | pass 345 | while not q_out.empty(): 346 | try: 347 | q_out.get_nowait() 348 | except Empty: 349 | pass 350 | 351 | del q_in, q_out, q_in_counter, q_out_counter, stop_process, model_warmup_complete 352 | _LOGGER.info("Done cleaning, exiting.") 353 | 354 | 355 | if __name__ == "__main__": 356 | # important for running applications that have been frozen for e.g. with PyInstaller 357 | multiprocessing.freeze_support() 358 | 359 | parser = argparse.ArgumentParser() 360 | parser.add_argument("--mode", type=InferencePipelineMode, choices=list(InferencePipelineMode)) 361 | parser.add_argument( 362 | "--noise-suppression-threshold", 363 | type=float, 364 | default=5, 365 | help="Threshold magnitude value for suppressing noise", 366 | ) 367 | parser.add_argument( 368 | "--callback-latency-ms", 369 | type=float, 370 | default=400, 371 | help="Latency", 372 | ) 373 | parser.add_argument( 374 | "--session-upload-path", 375 | type=str, 376 | default=None, 377 | help="path to store session audio segments within s3. if provided, data will be uploaded periodically.", 378 | ) 379 | parser.add_argument("--target-speaker", type=int, default=0) 380 | opt = parser.parse_args() 381 | 382 | # capture audio io device indices from the user 383 | input_device_idx, output_device_idx = get_audio_io_indices() 384 | 385 | opt.input_device_idx = input_device_idx 386 | opt.output_device_idx = output_device_idx 387 | _LOGGER.info(opt) 388 | 389 | stop_pipeline = Value("i", 0) 390 | try: 391 | run_inference_rt(opt, stop_pipeline=stop_pipeline) 392 | except (KeyboardInterrupt, Exception) as e: 393 | with stop_pipeline.get_lock(): 394 | stop_pipeline.value = 1 395 | -------------------------------------------------------------------------------- /services/desktop_app/LICENCE.txt: -------------------------------------------------------------------------------- 1 | END USER LICENSE AGREEMENT 2 | 3 | Last updated August 29, 2022 4 | 5 | 6 | 7 | MetaVoice is licensed to You (End-User) by MetaVoice Labs Inc., located and registered at 548 Market St #45420, San Francisco, California 94104-5401, United States ("Licensor"), for use only under the terms of this License Agreement. 8 | 9 | By downloading the Licensed Application from Apple's software distribution platform ("App Store"), and any update thereto (as permitted by this License Agreement), You indicate that You agree to be bound by all of the terms and conditions of this License Agreement, and that You accept this License Agreement. App Store is referred to in this License Agreement as "Services." 10 | 11 | The parties of this License Agreement acknowledge that the Services are not a Party to this License Agreement and are not bound by any provisions or obligations with regard to the Licensed Application, such as warranty, liability, maintenance and support thereof. MetaVoice Labs Inc., not the Services, is solely responsible for the Licensed Application and the content thereof. 12 | 13 | This License Agreement may not provide for usage rules for the Licensed Application that are in conflict with the latest Apple Media Services Terms and Conditions ("Usage Rules"). MetaVoice Labs Inc. acknowledges that it had the opportunity to review the Usage Rules and this License Agreement is not conflicting with them. 14 | 15 | MetaVoice when purchased or downloaded through the Services, is licensed to You for use only under the terms of this License Agreement. The Licensor reserves all rights not expressly granted to You. MetaVoice is to be used on devices that operate with Apple's operating systems ("iOS" and "Mac OS"). 16 | 17 | 18 | TABLE OF CONTENTS 19 | 20 | 1. THE APPLICATION 21 | 2. SCOPE OF LICENSE 22 | 3. TECHNICAL REQUIREMENTS 23 | 4. NO MAINTENANCE AND SUPPORT 24 | 5. USE OF DATA 25 | 6. USER-GENERATED CONTRIBUTIONS 26 | 7. CONTRIBUTION LICENSE 27 | 8. LIABILITY 28 | 9. WARRANTY 29 | 10. PRODUCT CLAIMS 30 | 11. LEGAL COMPLIANCE 31 | 12. CONTACT INFORMATION 32 | 13. TERMINATION 33 | 14. THIRD-PARTY TERMS OF AGREEMENTS AND BENEFICIARY 34 | 15. INTELLECTUAL PROPERTY RIGHTS 35 | 16. APPLICABLE LAW 36 | 17. MISCELLANEOUS 37 | 38 | 39 | 1. THE APPLICATION 40 | 41 | MetaVoice ("Licensed Application") is a piece of software created to To enable users to modify their voice in real-time for non-commercial & entertainment purposes. — and customized for iOS mobile devices ("Devices"). It is used to modify a users voice in real-time. 42 | 43 | The Licensed Application is not tailored to comply with industry-specific regulations (Health Insurance Portability and Accountability Act (HIPAA), Federal Information Security Management Act (FISMA), etc.), so if your interactions would be subjected to such laws, you may not use this Licensed Application. You may not use the Licensed Application in a way that would violate the Gramm-Leach-Bliley Act (GLBA). 44 | 45 | 46 | 2. SCOPE OF LICENSE 47 | 48 | 2.1 You are given a non-transferable, non-exclusive, non-sublicensable license to install and use the Licensed Application on any Devices that You (End-User) own or control and as permitted by the Usage Rules, with the exception that such Licensed Application may be accessed and used by other accounts associated with You (End-User, The Purchaser) via Family Sharing or volume purchasing. 49 | 50 | 2.2 This license will also govern any updates of the Licensed Application provided by Licensor that replace, repair, and/or supplement the first Licensed Application, unless a separate license is provided for such update, in which case the terms of that new license will govern. 51 | 52 | 2.3 You may not share or make the Licensed Application available to third parties (unless to the degree allowed by the Usage Rules, and with MetaVoice Labs Inc.'s prior written consent), sell, rent, lend, lease or otherwise redistribute the Licensed Application. 53 | 54 | 2.4 You may not reverse engineer, translate, disassemble, integrate, decompile, remove, modify, combine, create derivative works or updates of, adapt, or attempt to derive the source code of the Licensed Application, or any part thereof (except with MetaVoice Labs Inc.'s prior written consent). 55 | 56 | 2.5 You may not copy (excluding when expressly authorized by this license and the Usage Rules) or alter the Licensed Application or portions thereof. You may create and store copies only on devices that You own or control for backup keeping under the terms of this license, the Usage Rules, and any other terms and conditions that apply to the device or software used. You may not remove any intellectual property notices. You acknowledge that no unauthorized third parties may gain access to these copies at any time. If you sell your Devices to a third party, you must remove the Licensed Application from the Devices before doing so. 57 | 58 | 2.6 Violations of the obligations mentioned above, as well as the attempt of such infringement, may be subject to prosecution and damages. 59 | 60 | 2.7 Licensor reserves the right to modify the terms and conditions of licensing. 61 | 62 | 2.8 Nothing in this license should be interpreted to restrict third-party terms. When using the Licensed Application, You must ensure that You comply with applicable third-party terms and conditions. 63 | 64 | 65 | 3. TECHNICAL REQUIREMENTS 66 | 67 | 68 | 4. NO MAINTENANCE OR SUPPORT 69 | 70 | 4.1 MetaVoice Labs Inc. is not obligated, expressed or implied, to provide any maintenance, technical or other support for the Licensed Application. 71 | 72 | 4.2 MetaVoice Labs Inc. and the End-User acknowledge that the Services have no obligation whatsoever to furnish any maintenance and support services with respect to the Licensed Application. 73 | 74 | 75 | 5. USE OF DATA 76 | 77 | You acknowledge that Licensor will be able to access and adjust Your downloaded Licensed Application content and Your personal information, and that Licensor's use of such material and information is subject to Your legal agreements with Licensor and Licensor's privacy policy: https://themetavoice.xyz/privacy-policy. 78 | 79 | You acknowledge that the Licensor may periodically collect and use technical data and related information about your device, system, and application software, and peripherals, offer product support, facilitate the software updates, and for purposes of providing other services to you (if any) related to the Licensed Application. Licensor may also use this information to improve its products or to provide services or technologies to you, as long as it is in a form that does not personally identify you. 80 | 81 | 82 | 6. USER-GENERATED CONTRIBUTIONS 83 | 84 | The Licensed Application does not offer users to submit or post content. We may provide you with the opportunity to create, submit, post, display, transmit, perform, publish, distribute, or broadcast content and materials to us or in the Licensed Application, including but not limited to text, writings, video, audio, photographs, graphics, comments, suggestions, or personal information or other material (collectively, "Contributions"). Contributions may be viewable by other users of the Licensed Application and through third-party websites or applications. As such, any Contributions you transmit may be treated in accordance with the Licensed Application Privacy Policy. When you create or make available any Contributions, you thereby represent and warrant that: 85 | 86 | 1. The creation, distribution, transmission, public display, or performance, and the accessing, downloading, or copying of your Contributions do not and will not infringe the proprietary rights, including but not limited to the copyright, patent, trademark, trade secret, or moral rights of any third party. 87 | 2. You are the creator and owner of or have the necessary licenses, rights, consents, releases, and permissions to use and to authorize us, the Licensed Application, and other users of the Licensed Application to use your Contributions in any manner contemplated by the Licensed Application and this License Agreement. 88 | 3. You have the written consent, release, and/or permission of each and every identifiable individual person in your Contributions to use the name or likeness or each and every such identifiable individual person to enable inclusion and use of your Contributions in any manner contemplated by the Licensed Application and this License Agreement. 89 | 4. Your Contributions are not false, inaccurate, or misleading. 90 | 5. Your Contributions are not unsolicited or unauthorized advertising, promotional materials, pyramid schemes, chain letters, spam, mass mailings, or other forms of solicitation. 91 | 6. Your Contributions are not obscene, lewd, lascivious, filthy, violent, harassing, libelous, slanderous, or otherwise objectionable (as determined by us). 92 | 7. Your Contributions do not ridicule, mock, disparage, intimidate, or abuse anyone. 93 | 8. Your Contributions are not used to harass or threaten (in the legal sense of those terms) any other person and to promote violence against a specific person or class of people. 94 | 9. Your Contributions do not violate any applicable law, regulation, or rule. 95 | 10. Your Contributions do not violate the privacy or publicity rights of any third party. 96 | 11. Your Contributions do not violate any applicable law concerning child pornography, or otherwise intended to protect the health or well-being of minors. 97 | 12. Your Contributions do not include any offensive comments that are connected to race, national origin, gender, sexual preference, or physical handicap. 98 | 13. Your Contributions do not otherwise violate, or link to material that violates, any provision of this License Agreement, or any applicable law or regulation. 99 | 100 | Any use of the Licensed Application in violation of the foregoing violates this License Agreement and may result in, among other things, termination or suspension of your rights to use the Licensed Application. 101 | 102 | 103 | 7. CONTRIBUTION LICENSE 104 | 105 | You agree that we may access, store, process, and use any information and personal data that you provide following the terms of the Privacy Policy and your choices (including settings). 106 | 107 | By submitting suggestions of other feedback regarding the Licensed Application, you agree that we can use and share such feedback for any purpose without compensation to you. 108 | 109 | We do not assert any ownership over your Contributions. You retain full ownership of all of your Contributions and any intellectual property rights or other proprietary rights associated with your Contributions. We are not liable for any statements or representations in your Contributions provided by you in any area in the Licensed Application. You are solely responsible for your Contributions to the Licensed Application and you expressly agree to exonerate us from any and all responsibility and to refrain from any legal action against us regarding your Contributions. 110 | 111 | 112 | 8. LIABILITY 113 | 114 | 8.1 Licensor takes no accountability or responsibility for any damages caused due to a breach of duties according to Section 2 of this License Agreement. To avoid data loss, You are required to make use of backup functions of the Licensed Application to the extent allowed by applicable third-party terms and conditions of use. You are aware that in case of alterations or manipulations of the Licensed Application, You will not have access to the Licensed Application. 115 | 116 | 8.2 Licensor takes no accountability and responsibility in case of misuse of this technology in any way. 117 | 118 | 119 | 9. WARRANTY 120 | 121 | 9.1 Licensor warrants that the Licensed Application is free of spyware, trojan horses, viruses, or any other malware at the time of Your download. Licensor warrants that the Licensed Application works as described in the user documentation. 122 | 123 | 9.2 No warranty is provided for the Licensed Application that is not executable on the device, that has been unauthorizedly modified, handled inappropriately or culpably, combined or installed with inappropriate hardware or software, used with inappropriate accessories, regardless if by Yourself or by third parties, or if there are any other reasons outside of MetaVoice Labs Inc.'s sphere of influence that affect the executability of the Licensed Application. 124 | 125 | 9.3 You are required to inspect the Licensed Application immediately after installing it and notify MetaVoice Labs Inc. about issues discovered without delay by email provided in Product Claims. The defect report will be taken into consideration and further investigated if it has been emailed within a period of __________ days after discovery. 126 | 127 | 9.4 If we confirm that the Licensed Application is defective, MetaVoice Labs Inc. reserves a choice to remedy the situation either by means of solving the defect or substitute delivery. 128 | 129 | 9.5 In the event of any failure of the Licensed Application to conform to any applicable warranty, You may notify the Services Store Operator, and Your Licensed Application purchase price will be refunded to You. To the maximum extent permitted by applicable law, the Services Store Operator will have no other warranty obligation whatsoever with respect to the Licensed Application, and any other losses, claims, damages, liabilities, expenses, and costs attributable to any negligence to adhere to any warranty. 130 | 131 | 9.6 If the user is an entrepreneur, any claim based on faults expires after a statutory period of limitation amounting to twelve (12) months after the Licensed Application was made available to the user. The statutory periods of limitation given by law apply for users who are consumers. 132 | 133 | 134 | 10. PRODUCT CLAIMS 135 | 136 | MetaVoice Labs Inc. and the End-User acknowledge that MetaVoice Labs Inc., and not the Services, is responsible for addressing any claims of the End-User or any third party relating to the Licensed Application or the End-User’s possession and/or use of that Licensed Application, including, but not limited to: 137 | 138 | (i) product liability claims; 139 | 140 | (ii) any claim that the Licensed Application fails to conform to any applicable legal or regulatory requirement; and 141 | 142 | (iii) claims arising under consumer protection, privacy, or similar legislation, including in connection with Your Licensed Application’s use of the HealthKit and HomeKit. 143 | 144 | 145 | 11. LEGAL COMPLIANCE 146 | 147 | You represent and warrant that You are not located in a country that is subject to a US Government embargo, or that has been designated by the US Government as a "terrorist supporting" country; and that You are not listed on any US Government list of prohibited or restricted parties. 148 | 149 | 150 | 12. CONTACT INFORMATION 151 | 152 | For general inquiries, complaints, questions or claims concerning the Licensed Application, please contact: 153 | 154 | MetaVoice 155 | 548 Market St #45420 156 | San Francisco, CA 94104-5401 157 | United States 158 | gm@themetavoice.xyz 159 | 160 | 161 | 13. TERMINATION 162 | 163 | The license is valid until terminated by MetaVoice Labs Inc. or by You. Your rights under this license will terminate automatically and without notice from MetaVoice Labs Inc. if You fail to adhere to any term(s) of this license. Upon License termination, You shall stop all use of the Licensed Application, and destroy all copies, full or partial, of the Licensed Application. 164 | 165 | 166 | 14. THIRD-PARTY TERMS OF AGREEMENTS AND BENEFICIARY 167 | 168 | MetaVoice Labs Inc. represents and warrants that MetaVoice Labs Inc. will comply with applicable third-party terms of agreement when using Licensed Application. 169 | 170 | In Accordance with Section 9 of the "Instructions for Minimum Terms of Developer's End-User License Agreement," Apple's subsidiaries shall be third-party beneficiaries of this End User License Agreement and — upon Your acceptance of the terms and conditions of this License Agreement, Apple will have the right (and will be deemed to have accepted the right) to enforce this End User License Agreement against You as a third-party beneficiary thereof. 171 | 172 | 173 | 15. INTELLECTUAL PROPERTY RIGHTS 174 | 175 | MetaVoice Labs Inc. and the End-User acknowledge that, in the event of any third-party claim that the Licensed Application or the End-User's possession and use of that Licensed Application infringes on the third party's intellectual property rights, MetaVoice Labs Inc., and not the Services, will be solely responsible for the investigation, defense, settlement, and discharge or any such intellectual property infringement claims. 176 | 177 | 178 | 16. APPLICABLE LAW 179 | 180 | This License Agreement is governed by the laws of the State of California excluding its conflicts of law rules. 181 | 182 | 183 | 17. MISCELLANEOUS 184 | 185 | 17.1 If any of the terms of this agreement should be or become invalid, the validity of the remaining provisions shall not be affected. Invalid terms will be replaced by valid ones formulated in a way that will achieve the primary purpose. 186 | 187 | 17.2 Collateral agreements, changes and amendments are only valid if laid down in writing. The preceding clause can only be waived in writing. 188 | This EULA was created using Termly's EULA Generator. 189 | -------------------------------------------------------------------------------- /services/desktop_app/src/components/Conversion.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from "react"; 2 | import Form from "react-bootstrap/Form"; 3 | import FloatingLabel from "react-bootstrap/FloatingLabel"; 4 | import Container from "react-bootstrap/Container"; 5 | import Button from "react-bootstrap/Button"; 6 | import Badge from "react-bootstrap/Badge"; 7 | import Spinner from "react-bootstrap/Spinner"; 8 | import Loading from "./Loading"; 9 | import InputGroup from "react-bootstrap/InputGroup"; 10 | import Stack from "react-bootstrap/Stack"; 11 | import Accordion from "react-bootstrap/Accordion"; 12 | import './Conversion.css'; 13 | import PreferencesModal, { settingsAtom } from "./PreferencesModal"; 14 | import { SERVER_BASE_URL } from "../constants"; 15 | import SessionFeedbackModal from "./SessionFeedbackModal"; 16 | import posthog from "posthog-js"; 17 | import { useAtom } from "jotai"; 18 | import Speaker from "./Speaker"; 19 | import logoImage from "../../assets/MetaVoice Live Logo - Dark Transparent.png"; 20 | import { getSpeakers } from "../api"; 21 | 22 | var framesError = true; 23 | 24 | export default function Conversion({ email, issuer }) { 25 | const [settings, setSettings] = useAtom(settingsAtom); 26 | const [deviceMap, setDeviceMap] = useState(); 27 | const [isServerOnline, setIsServerOnline] = useState(false); 28 | const [buttonClicked, setButtonClicked] = useState(false); 29 | const [isProcessing, setIsProcessing] = useState(false); 30 | const [conversionRunning, setConversionRunning] = useState(false); 31 | // audio states 32 | const [originalAudio, setOriginalAudio] = useState(null); 33 | const [convertedAudio, setConvertedAudio] = useState(null); 34 | const [hackFramesError, setFramesError] = useState(true); 35 | const [speakers, setSpeakers] = useState([]); 36 | 37 | useEffect(() => { 38 | (async () => { 39 | // using effect instead of memo so we can display loading screen 40 | const speakers = await getSpeakers(); 41 | 42 | if (speakers.length === 0) { 43 | throw new Error("No speakers found"); 44 | } 45 | 46 | setSpeakers(speakers); 47 | })() 48 | }, []); 49 | 50 | const registerUserWithServer = () => { 51 | // TODO sidroopdaska: refactor into a singular settings object 52 | const cached = window.localStorage.getItem("MV_SHARE_DATA"); 53 | const shareData = cached ? cached === "true" : true; 54 | 55 | fetch( 56 | [ 57 | SERVER_BASE_URL, 58 | "/register-user", 59 | "?email=", email, 60 | "&issuer=", issuer, 61 | "&share_data=", shareData, 62 | "&noise_suppression=", settings['noise-suppression-threshold'], 63 | "&callback_latency_ms_=", settings['callback-latency-ms'], 64 | ].join(""), 65 | { method: "GET" } 66 | ).catch((error) => { 67 | console.log(`register user failed: ${error}`); 68 | }); 69 | 70 | posthog.capture("user registered with server", { 71 | email: email, 72 | issuer: issuer, 73 | shareData: shareData, 74 | ...settings, 75 | }); 76 | }; 77 | 78 | const checkServerIsOnline = () => { 79 | fetch(`${SERVER_BASE_URL}/is-alive`, { method: "GET" }) 80 | .then((_response) => { 81 | console.log("server online"); 82 | 83 | registerUserWithServer(); 84 | setIsServerOnline(true); 85 | }) 86 | .catch((error) => { 87 | console.log("server offline", error); 88 | setTimeout(checkServerIsOnline, 2000); 89 | }); 90 | }; 91 | 92 | useEffect(() => { 93 | if (isServerOnline) return; 94 | checkServerIsOnline(); 95 | }, []); 96 | 97 | const fetchDeviceMap = () => { 98 | fetch(`${SERVER_BASE_URL}/device-map?mode=prod`, { method: "GET" }) 99 | .then((response) => { 100 | if (!response.ok) throw Error(response.statusText); 101 | return response.json(); 102 | }) 103 | .then((data) => { 104 | setDeviceMap(data); 105 | }) 106 | .catch((error) => { 107 | console.log(`Error: ${error}`); 108 | }); 109 | }; 110 | 111 | useEffect(() => { 112 | // Fetch the device map when the server comes online 113 | if (!isServerOnline) return; 114 | fetchDeviceMap(); 115 | var ws = new WebSocket("ws://127.0.0.1:58000/ws-frame-health"); 116 | ws.onerror = (error) => { 117 | console.log(error); 118 | }; 119 | ws.onmessage = function (event) { 120 | if (JSON.parse(event.data)[0] == 0) { 121 | framesError = false; 122 | setFramesError(false); 123 | } else { 124 | framesError = true; 125 | setFramesError(true); 126 | } 127 | }; 128 | }, [isServerOnline]); 129 | 130 | const renderDeviceSelect = (mode) => { 131 | // mode can be inputs/outputs 132 | let optionsList = [ 133 | , 136 | ]; 137 | if (deviceMap) { 138 | deviceMap[mode].forEach((device) => { 139 | optionsList.push( 140 | 146 | ); 147 | }); 148 | } 149 | 150 | return optionsList; 151 | }; 152 | 153 | const handleInputDeviceChange = (event) => { 154 | setSettings({ ...settings, inputDeviceId: event.target.value }) 155 | }; 156 | 157 | const handleOutputDeviceChange = (event) => { 158 | setSettings({ ...settings, outputDeviceId: event.target.value }) 159 | }; 160 | 161 | const handleTargetSpeakerChange = (idx) => { 162 | setSettings({ ...settings, targetSpeakerId: idx }) 163 | }; 164 | 165 | const handleButtonClick = () => { 166 | let buttonClickedNewState = !buttonClicked; 167 | 168 | if (buttonClickedNewState) { 169 | convertStartTime = Date.now(); 170 | posthog.capture("user requested conversion start", { 171 | email: email, 172 | appVersion: process.env.npm_package_version, 173 | targetSpeaker: settings.targetSpeakerId, 174 | }); 175 | fetch( 176 | [ 177 | SERVER_BASE_URL, 178 | "/start-convert", 179 | "?input_device_idx=", settings.inputDeviceId, 180 | "&output_device_idx=", settings.outputDeviceId, 181 | "&app_version=", process.env.npm_package_version, 182 | "&target_speaker=", settings.targetSpeakerId, 183 | ].join(""), 184 | { method: "GET", keepalive: true } 185 | ) 186 | .then((_response) => { 187 | setIsProcessing(false); 188 | // TODO: @sidroopdaska, add comment - why did we move setButtonClicked(buttonClickedNewState) inside 189 | // each of these statements, instead of after it? 190 | setButtonClicked(buttonClickedNewState); 191 | setConversionRunning(true); 192 | 193 | posthog.capture("user started conversion", { 194 | email: email, 195 | appVersion: process.env.npm_package_version, 196 | targetSpeaker: settings.targetSpeakerId, 197 | }); 198 | }) 199 | .catch((error) => { 200 | // TODO: toast, send auth info 201 | console.log(error); 202 | posthog.capture("user conversion start failed", { 203 | email: email, 204 | appVersion: process.env.npm_package_version, 205 | targetSpeaker: settings.targetSpeakerId, 206 | error: error, 207 | }); 208 | setIsProcessing(false); 209 | setButtonClicked(buttonClickedNewState); 210 | }); 211 | } else { 212 | posthog.capture("user requested conversion stop", { 213 | email: email, 214 | appVersion: process.env.npm_package_version, 215 | targetSpeaker: settings.targetSpeakerId, 216 | }); 217 | fetch(`${SERVER_BASE_URL}/stop-convert`, { 218 | method: "GET", 219 | keepalive: true, 220 | }) 221 | .then(async (_response) => { 222 | let latencyRecord = null; 223 | try { 224 | // TODO: below works, 225 | latencyRecord = await _response.json(); 226 | latencyRecord = latencyRecord["latency_records"]; 227 | } catch (error) { 228 | latencyRecord = error; 229 | console.log(error); 230 | } 231 | 232 | posthog.capture("user stopped conversion", { 233 | email: email, 234 | appVersion: process.env.npm_package_version, 235 | targetSpeaker: settings.targetSpeakerId, 236 | latencyRecord: latencyRecord, 237 | }); 238 | setConversionRunning(false); 239 | 240 | let responses = await Promise.all([ 241 | fetch(`${SERVER_BASE_URL}/audio?audio_type=original`, { 242 | method: "GET", 243 | }), 244 | fetch(`${SERVER_BASE_URL}/audio?audio_type=converted`, { 245 | method: "GET", 246 | }), 247 | ]); 248 | let originalBlob = await responses[0].blob(); 249 | let convertedBlob = await responses[1].blob(); 250 | 251 | const originalBlobUrl = URL.createObjectURL(originalBlob); 252 | setOriginalAudio(originalBlobUrl); 253 | setConvertedAudio(URL.createObjectURL(convertedBlob)); 254 | 255 | getBlobDuration(originalBlobUrl).then((duration) => { 256 | posthog.capture("user conversion processed", { 257 | email: email, 258 | appVersion: process.env.npm_package_version, 259 | targetSpeaker: settings.targetSpeakerId, 260 | latencyRecord: latencyRecord, 261 | duration, 262 | }) 263 | }); 264 | 265 | setIsProcessing(false); 266 | setButtonClicked(buttonClickedNewState); 267 | }) 268 | .catch((error) => { 269 | posthog.capture("user conversion stop failed", { 270 | email: email, 271 | appVersion: process.env.npm_package_version, 272 | targetSpeaker: settings.targetSpeakerId, 273 | error: error, 274 | }); 275 | console.log(error); 276 | setIsProcessing(false); 277 | setButtonClicked(buttonClickedNewState); 278 | }); 279 | } 280 | 281 | setIsProcessing(true); 282 | }; 283 | 284 | const renderAudioAccordion = () => { 285 | return ( 286 | 287 | 288 | Review & Share Session 289 | 290 |
291 |
292 |
293 | Original Identity 294 |
295 |
297 |
298 |
Target Identity
299 |
301 |
302 | 305 |
306 |
307 |
308 | ); 309 | }; 310 | 311 | return ( 312 | <> 313 | 317 | 318 | logo 324 |
325 | 326 | {/* TODO: reinstate in the future */} 327 | {/* Founding Member */} 328 | 329 | 330 |
331 |
332 | 333 | {conversionRunning && ( 334 |
335 | 343 | 347 | 348 | {framesError ? "Frames dropping" : "Frames OK"} 349 |
350 | )} 351 |
352 | {/* # TODO (outdated?): add button handlers for actions on each voice */} 353 | {speakers.map((speaker) => { 354 | return ( 355 | { 360 | handleTargetSpeakerChange(speaker.id); 361 | }} 362 | disabled={buttonClicked || isProcessing} 363 | selected={settings.targetSpeakerId === speaker.id} 364 | /> 365 | ) 366 | })} 367 |
368 | 369 |
370 | 371 | 372 | 373 | 374 | 378 | 384 | {renderDeviceSelect("inputs")} 385 | 386 | 387 | 388 |
389 | 390 |
391 | 392 | 393 | 394 | 395 | 399 | 405 | {renderDeviceSelect("outputs")} 406 | 407 | 408 | 409 |
410 | 411 |
412 | 445 |
446 | {renderAudioAccordion()} 447 |
448 | 449 | ); 450 | } 451 | 452 | // modified from https://github.com/evictor/get-blob-duration/blob/master/src/getBlobDuration.js 453 | function getBlobDuration(blobUrl) { 454 | const tempVideoEl = document.createElement('video') 455 | 456 | const durationP = new Promise((resolve, reject) => { 457 | tempVideoEl.addEventListener('loadedmetadata', () => { 458 | // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=642012 459 | if(tempVideoEl.duration === Infinity) { 460 | tempVideoEl.currentTime = Number.MAX_SAFE_INTEGER 461 | tempVideoEl.ontimeupdate = () => { 462 | tempVideoEl.ontimeupdate = null 463 | resolve(tempVideoEl.duration) 464 | tempVideoEl.currentTime = 0 465 | } 466 | } 467 | // Normal behavior 468 | else 469 | resolve(tempVideoEl.duration) 470 | }) 471 | tempVideoEl.onerror = (event) => reject(event.target.error) 472 | }) 473 | 474 | tempVideoEl.src = blobUrl; 475 | 476 | return durationP 477 | } -------------------------------------------------------------------------------- /debug/collect_env.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | # Unlike the rest of the PyTorch this file must be python2 compliant. 4 | # This script outputs relevant system environment info 5 | # Run it with `python collect_env.py`. 6 | import datetime 7 | import locale 8 | import re 9 | import subprocess 10 | import sys 11 | import os 12 | from collections import namedtuple 13 | 14 | 15 | try: 16 | import torch 17 | TORCH_AVAILABLE = True 18 | except (ImportError, NameError, AttributeError, OSError): 19 | TORCH_AVAILABLE = False 20 | 21 | # System Environment Information 22 | SystemEnv = namedtuple('SystemEnv', [ 23 | 'torch_version', 24 | 'is_debug_build', 25 | 'cuda_compiled_version', 26 | 'gcc_version', 27 | 'clang_version', 28 | 'cmake_version', 29 | 'os', 30 | 'libc_version', 31 | 'python_version', 32 | 'python_platform', 33 | 'is_cuda_available', 34 | 'cuda_runtime_version', 35 | 'nvidia_driver_version', 36 | 'nvidia_gpu_models', 37 | 'cudnn_version', 38 | 'pip_version', # 'pip' or 'pip3' 39 | 'pip_packages', 40 | 'conda_packages', 41 | 'hip_compiled_version', 42 | 'hip_runtime_version', 43 | 'miopen_runtime_version', 44 | 'caching_allocator_config', 45 | 'is_xnnpack_available', 46 | ]) 47 | 48 | 49 | def run(command): 50 | """Returns (return-code, stdout, stderr)""" 51 | p = subprocess.Popen(command, stdout=subprocess.PIPE, 52 | stderr=subprocess.PIPE, shell=True) 53 | raw_output, raw_err = p.communicate() 54 | rc = p.returncode 55 | if get_platform() == 'win32': 56 | enc = 'oem' 57 | else: 58 | enc = locale.getpreferredencoding() 59 | output = raw_output.decode(enc) 60 | err = raw_err.decode(enc) 61 | return rc, output.strip(), err.strip() 62 | 63 | 64 | def run_and_read_all(run_lambda, command): 65 | """Runs command using run_lambda; reads and returns entire output if rc is 0""" 66 | rc, out, _ = run_lambda(command) 67 | if rc != 0: 68 | return None 69 | return out 70 | 71 | 72 | def run_and_parse_first_match(run_lambda, command, regex): 73 | """Runs command using run_lambda, returns the first regex match if it exists""" 74 | rc, out, _ = run_lambda(command) 75 | if rc != 0: 76 | return None 77 | match = re.search(regex, out) 78 | if match is None: 79 | return None 80 | return match.group(1) 81 | 82 | def run_and_return_first_line(run_lambda, command): 83 | """Runs command using run_lambda and returns first line if output is not empty""" 84 | rc, out, _ = run_lambda(command) 85 | if rc != 0: 86 | return None 87 | return out.split('\n')[0] 88 | 89 | 90 | def get_conda_packages(run_lambda): 91 | conda = os.environ.get('CONDA_EXE', 'conda') 92 | out = run_and_read_all(run_lambda, "{} list".format(conda)) 93 | if out is None: 94 | return out 95 | 96 | return "\n".join( 97 | line 98 | for line in out.splitlines() 99 | if not line.startswith("#") 100 | and any( 101 | name in line 102 | for name in { 103 | "torch", 104 | "numpy", 105 | "cudatoolkit", 106 | "soumith", 107 | "mkl", 108 | "magma", 109 | "mkl", 110 | } 111 | ) 112 | ) 113 | 114 | def get_gcc_version(run_lambda): 115 | return run_and_parse_first_match(run_lambda, 'gcc --version', r'gcc (.*)') 116 | 117 | def get_clang_version(run_lambda): 118 | return run_and_parse_first_match(run_lambda, 'clang --version', r'clang version (.*)') 119 | 120 | 121 | def get_cmake_version(run_lambda): 122 | return run_and_parse_first_match(run_lambda, 'cmake --version', r'cmake (.*)') 123 | 124 | 125 | def get_nvidia_driver_version(run_lambda): 126 | if get_platform() == 'darwin': 127 | cmd = 'kextstat | grep -i cuda' 128 | return run_and_parse_first_match(run_lambda, cmd, 129 | r'com[.]nvidia[.]CUDA [(](.*?)[)]') 130 | smi = get_nvidia_smi() 131 | return run_and_parse_first_match(run_lambda, smi, r'Driver Version: (.*?) ') 132 | 133 | 134 | def get_gpu_info(run_lambda): 135 | if get_platform() == 'darwin' or (TORCH_AVAILABLE and hasattr(torch.version, 'hip') and torch.version.hip is not None): 136 | if TORCH_AVAILABLE and torch.cuda.is_available(): 137 | return torch.cuda.get_device_name(None) 138 | return None 139 | smi = get_nvidia_smi() 140 | uuid_regex = re.compile(r' \(UUID: .+?\)') 141 | rc, out, _ = run_lambda(smi + ' -L') 142 | if rc != 0: 143 | return None 144 | # Anonymize GPUs by removing their UUID 145 | return re.sub(uuid_regex, '', out) 146 | 147 | 148 | def get_running_cuda_version(run_lambda): 149 | return run_and_parse_first_match(run_lambda, 'nvcc --version', r'release .+ V(.*)') 150 | 151 | 152 | def get_cudnn_version(run_lambda): 153 | """This will return a list of libcudnn.so; it's hard to tell which one is being used""" 154 | if get_platform() == 'win32': 155 | system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows') 156 | cuda_path = os.environ.get('CUDA_PATH', "%CUDA_PATH%") 157 | where_cmd = os.path.join(system_root, 'System32', 'where') 158 | cudnn_cmd = '{} /R "{}\\bin" cudnn*.dll'.format(where_cmd, cuda_path) 159 | elif get_platform() == 'darwin': 160 | # CUDA libraries and drivers can be found in /usr/local/cuda/. See 161 | # https://docs.nvidia.com/cuda/cuda-installation-guide-mac-os-x/index.html#install 162 | # https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html#installmac 163 | # Use CUDNN_LIBRARY when cudnn library is installed elsewhere. 164 | cudnn_cmd = 'ls /usr/local/cuda/lib/libcudnn*' 165 | else: 166 | cudnn_cmd = 'ldconfig -p | grep libcudnn | rev | cut -d" " -f1 | rev' 167 | rc, out, _ = run_lambda(cudnn_cmd) 168 | # find will return 1 if there are permission errors or if not found 169 | if len(out) == 0 or (rc != 1 and rc != 0): 170 | l = os.environ.get('CUDNN_LIBRARY') 171 | if l is not None and os.path.isfile(l): 172 | return os.path.realpath(l) 173 | return None 174 | files_set = set() 175 | for fn in out.split('\n'): 176 | fn = os.path.realpath(fn) # eliminate symbolic links 177 | if os.path.isfile(fn): 178 | files_set.add(fn) 179 | if not files_set: 180 | return None 181 | # Alphabetize the result because the order is non-deterministic otherwise 182 | files = list(sorted(files_set)) 183 | if len(files) == 1: 184 | return files[0] 185 | result = '\n'.join(files) 186 | return 'Probably one of the following:\n{}'.format(result) 187 | 188 | 189 | def get_nvidia_smi(): 190 | # Note: nvidia-smi is currently available only on Windows and Linux 191 | smi = 'nvidia-smi' 192 | if get_platform() == 'win32': 193 | system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows') 194 | program_files_root = os.environ.get('PROGRAMFILES', 'C:\\Program Files') 195 | legacy_path = os.path.join(program_files_root, 'NVIDIA Corporation', 'NVSMI', smi) 196 | new_path = os.path.join(system_root, 'System32', smi) 197 | smis = [new_path, legacy_path] 198 | for candidate_smi in smis: 199 | if os.path.exists(candidate_smi): 200 | smi = '"{}"'.format(candidate_smi) 201 | break 202 | return smi 203 | 204 | 205 | def get_platform(): 206 | if sys.platform.startswith('linux'): 207 | return 'linux' 208 | elif sys.platform.startswith('win32'): 209 | return 'win32' 210 | elif sys.platform.startswith('cygwin'): 211 | return 'cygwin' 212 | elif sys.platform.startswith('darwin'): 213 | return 'darwin' 214 | else: 215 | return sys.platform 216 | 217 | 218 | def get_mac_version(run_lambda): 219 | return run_and_parse_first_match(run_lambda, 'sw_vers -productVersion', r'(.*)') 220 | 221 | 222 | def get_windows_version(run_lambda): 223 | system_root = os.environ.get('SYSTEMROOT', 'C:\\Windows') 224 | wmic_cmd = os.path.join(system_root, 'System32', 'Wbem', 'wmic') 225 | findstr_cmd = os.path.join(system_root, 'System32', 'findstr') 226 | return run_and_read_all(run_lambda, '{} os get Caption | {} /v Caption'.format(wmic_cmd, findstr_cmd)) 227 | 228 | 229 | def get_lsb_version(run_lambda): 230 | return run_and_parse_first_match(run_lambda, 'lsb_release -a', r'Description:\t(.*)') 231 | 232 | 233 | def check_release_file(run_lambda): 234 | return run_and_parse_first_match(run_lambda, 'cat /etc/*-release', 235 | r'PRETTY_NAME="(.*)"') 236 | 237 | 238 | def get_os(run_lambda): 239 | from platform import machine 240 | platform = get_platform() 241 | 242 | if platform == 'win32' or platform == 'cygwin': 243 | return get_windows_version(run_lambda) 244 | 245 | if platform == 'darwin': 246 | version = get_mac_version(run_lambda) 247 | if version is None: 248 | return None 249 | return 'macOS {} ({})'.format(version, machine()) 250 | 251 | if platform == 'linux': 252 | # Ubuntu/Debian based 253 | desc = get_lsb_version(run_lambda) 254 | if desc is not None: 255 | return '{} ({})'.format(desc, machine()) 256 | 257 | # Try reading /etc/*-release 258 | desc = check_release_file(run_lambda) 259 | if desc is not None: 260 | return '{} ({})'.format(desc, machine()) 261 | 262 | return '{} ({})'.format(platform, machine()) 263 | 264 | # Unknown platform 265 | return platform 266 | 267 | 268 | def get_python_platform(): 269 | import platform 270 | return platform.platform() 271 | 272 | 273 | def get_libc_version(): 274 | import platform 275 | if get_platform() != 'linux': 276 | return 'N/A' 277 | return '-'.join(platform.libc_ver()) 278 | 279 | 280 | def get_pip_packages(run_lambda): 281 | """Returns `pip list` output. Note: will also find conda-installed pytorch 282 | and numpy packages.""" 283 | # People generally have `pip` as `pip` or `pip3` 284 | # But here it is incoved as `python -mpip` 285 | def run_with_pip(pip): 286 | out = run_and_read_all(run_lambda, "{} list --format=freeze".format(pip)) 287 | return "\n".join( 288 | line 289 | for line in out.splitlines() 290 | if any( 291 | name in line 292 | for name in { 293 | "torch", 294 | "numpy", 295 | "mypy", 296 | } 297 | ) 298 | ) 299 | 300 | pip_version = 'pip3' if sys.version[0] == '3' else 'pip' 301 | out = run_with_pip(sys.executable + ' -mpip') 302 | 303 | return pip_version, out 304 | 305 | 306 | def get_cachingallocator_config(): 307 | ca_config = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', '') 308 | return ca_config 309 | 310 | def is_xnnpack_available(): 311 | if TORCH_AVAILABLE: 312 | import torch.backends.xnnpack 313 | return str(torch.backends.xnnpack.enabled) # type: ignore[attr-defined] 314 | else: 315 | return "N/A" 316 | 317 | def get_env_info(): 318 | run_lambda = run 319 | pip_version, pip_list_output = get_pip_packages(run_lambda) 320 | 321 | if TORCH_AVAILABLE: 322 | version_str = torch.__version__ 323 | debug_mode_str = str(torch.version.debug) 324 | cuda_available_str = str(torch.cuda.is_available()) 325 | cuda_version_str = torch.version.cuda 326 | if not hasattr(torch.version, 'hip') or torch.version.hip is None: # cuda version 327 | hip_compiled_version = hip_runtime_version = miopen_runtime_version = 'N/A' 328 | else: # HIP version 329 | cfg = torch._C._show_config().split('\n') 330 | hip_runtime_version = [s.rsplit(None, 1)[-1] for s in cfg if 'HIP Runtime' in s][0] 331 | miopen_runtime_version = [s.rsplit(None, 1)[-1] for s in cfg if 'MIOpen' in s][0] 332 | cuda_version_str = 'N/A' 333 | hip_compiled_version = torch.version.hip 334 | else: 335 | version_str = debug_mode_str = cuda_available_str = cuda_version_str = 'N/A' 336 | hip_compiled_version = hip_runtime_version = miopen_runtime_version = 'N/A' 337 | 338 | sys_version = sys.version.replace("\n", " ") 339 | 340 | return SystemEnv( 341 | torch_version=version_str, 342 | is_debug_build=debug_mode_str, 343 | python_version='{} ({}-bit runtime)'.format(sys_version, sys.maxsize.bit_length() + 1), 344 | python_platform=get_python_platform(), 345 | is_cuda_available=cuda_available_str, 346 | cuda_compiled_version=cuda_version_str, 347 | cuda_runtime_version=get_running_cuda_version(run_lambda), 348 | nvidia_gpu_models=get_gpu_info(run_lambda), 349 | nvidia_driver_version=get_nvidia_driver_version(run_lambda), 350 | cudnn_version=get_cudnn_version(run_lambda), 351 | hip_compiled_version=hip_compiled_version, 352 | hip_runtime_version=hip_runtime_version, 353 | miopen_runtime_version=miopen_runtime_version, 354 | pip_version=pip_version, 355 | pip_packages=pip_list_output, 356 | conda_packages=get_conda_packages(run_lambda), 357 | os=get_os(run_lambda), 358 | libc_version=get_libc_version(), 359 | gcc_version=get_gcc_version(run_lambda), 360 | clang_version=get_clang_version(run_lambda), 361 | cmake_version=get_cmake_version(run_lambda), 362 | caching_allocator_config=get_cachingallocator_config(), 363 | is_xnnpack_available=is_xnnpack_available(), 364 | ) 365 | 366 | env_info_fmt = """ 367 | PyTorch version: {torch_version} 368 | Is debug build: {is_debug_build} 369 | CUDA used to build PyTorch: {cuda_compiled_version} 370 | ROCM used to build PyTorch: {hip_compiled_version} 371 | 372 | OS: {os} 373 | GCC version: {gcc_version} 374 | Clang version: {clang_version} 375 | CMake version: {cmake_version} 376 | Libc version: {libc_version} 377 | 378 | Python version: {python_version} 379 | Python platform: {python_platform} 380 | Is CUDA available: {is_cuda_available} 381 | CUDA runtime version: {cuda_runtime_version} 382 | GPU models and configuration: {nvidia_gpu_models} 383 | Nvidia driver version: {nvidia_driver_version} 384 | cuDNN version: {cudnn_version} 385 | HIP runtime version: {hip_runtime_version} 386 | MIOpen runtime version: {miopen_runtime_version} 387 | Is XNNPACK available: {is_xnnpack_available} 388 | 389 | Versions of relevant libraries: 390 | {pip_packages} 391 | {conda_packages} 392 | """.strip() 393 | 394 | 395 | def pretty_str(envinfo): 396 | def replace_nones(dct, replacement='Could not collect'): 397 | for key in dct.keys(): 398 | if dct[key] is not None: 399 | continue 400 | dct[key] = replacement 401 | return dct 402 | 403 | def replace_bools(dct, true='Yes', false='No'): 404 | for key in dct.keys(): 405 | if dct[key] is True: 406 | dct[key] = true 407 | elif dct[key] is False: 408 | dct[key] = false 409 | return dct 410 | 411 | def prepend(text, tag='[prepend]'): 412 | lines = text.split('\n') 413 | updated_lines = [tag + line for line in lines] 414 | return '\n'.join(updated_lines) 415 | 416 | def replace_if_empty(text, replacement='No relevant packages'): 417 | if text is not None and len(text) == 0: 418 | return replacement 419 | return text 420 | 421 | def maybe_start_on_next_line(string): 422 | # If `string` is multiline, prepend a \n to it. 423 | if string is not None and len(string.split('\n')) > 1: 424 | return '\n{}\n'.format(string) 425 | return string 426 | 427 | mutable_dict = envinfo._asdict() 428 | 429 | # If nvidia_gpu_models is multiline, start on the next line 430 | mutable_dict['nvidia_gpu_models'] = \ 431 | maybe_start_on_next_line(envinfo.nvidia_gpu_models) 432 | 433 | # If the machine doesn't have CUDA, report some fields as 'No CUDA' 434 | dynamic_cuda_fields = [ 435 | 'cuda_runtime_version', 436 | 'nvidia_gpu_models', 437 | 'nvidia_driver_version', 438 | ] 439 | all_cuda_fields = dynamic_cuda_fields + ['cudnn_version'] 440 | all_dynamic_cuda_fields_missing = all( 441 | mutable_dict[field] is None for field in dynamic_cuda_fields) 442 | if TORCH_AVAILABLE and not torch.cuda.is_available() and all_dynamic_cuda_fields_missing: 443 | for field in all_cuda_fields: 444 | mutable_dict[field] = 'No CUDA' 445 | if envinfo.cuda_compiled_version is None: 446 | mutable_dict['cuda_compiled_version'] = 'None' 447 | 448 | # Replace True with Yes, False with No 449 | mutable_dict = replace_bools(mutable_dict) 450 | 451 | # Replace all None objects with 'Could not collect' 452 | mutable_dict = replace_nones(mutable_dict) 453 | 454 | # If either of these are '', replace with 'No relevant packages' 455 | mutable_dict['pip_packages'] = replace_if_empty(mutable_dict['pip_packages']) 456 | mutable_dict['conda_packages'] = replace_if_empty(mutable_dict['conda_packages']) 457 | 458 | # Tag conda and pip packages with a prefix 459 | # If they were previously None, they'll show up as ie '[conda] Could not collect' 460 | if mutable_dict['pip_packages']: 461 | mutable_dict['pip_packages'] = prepend(mutable_dict['pip_packages'], 462 | '[{}] '.format(envinfo.pip_version)) 463 | if mutable_dict['conda_packages']: 464 | mutable_dict['conda_packages'] = prepend(mutable_dict['conda_packages'], 465 | '[conda] ') 466 | return env_info_fmt.format(**mutable_dict) 467 | 468 | 469 | def get_pretty_env_info(): 470 | return pretty_str(get_env_info()) 471 | 472 | 473 | def main(): 474 | print("Collecting environment information...") 475 | output = get_pretty_env_info() 476 | print(output) 477 | 478 | if TORCH_AVAILABLE and hasattr(torch, 'utils') and hasattr(torch.utils, '_crash_handler'): 479 | minidump_dir = torch.utils._crash_handler.DEFAULT_MINIDUMP_DIR 480 | if sys.platform == "linux" and os.path.exists(minidump_dir): 481 | dumps = [os.path.join(minidump_dir, dump) for dump in os.listdir(minidump_dir)] 482 | latest = max(dumps, key=os.path.getctime) 483 | ctime = os.path.getctime(latest) 484 | creation_time = datetime.datetime.fromtimestamp(ctime).strftime('%Y-%m-%d %H:%M:%S') 485 | msg = "\n*** Detected a minidump at {} created on {}, ".format(latest, creation_time) + \ 486 | "if this is related to your bug please include it when you file a report ***" 487 | print(msg, file=sys.stderr) 488 | 489 | 490 | 491 | if __name__ == '__main__': 492 | main() 493 | -------------------------------------------------------------------------------- /services/desktop_app/main.js: -------------------------------------------------------------------------------- 1 | // Modules to control application life and create native browser window 2 | const { app, BrowserWindow, shell, systemPreferences, ipcMain, protocol, session } = require('electron'); 3 | const path = require('path'); 4 | const IS_DEV = process.env.NODE_ENV === 'dev'; 5 | const windowStateKeeper = require('electron-window-state'); 6 | 7 | const fs = require('fs'); 8 | const request = require("request"); 9 | const { URL } = require("url"); 10 | 11 | const unzipper = require('unzipper'); 12 | const package = require('./package.json'); 13 | const { deferPromise, checkNeedsNewVersion, findFreePort, notify, warnOnUnsupportedPlatform, updateMvml } = require('./util'); 14 | 15 | ipcMain.handle('request-app-version', async (event, ...args) => { 16 | return app.getVersion(); 17 | }); 18 | 19 | // TODO log to file. 20 | // electron-log had odd issues, should look for another solution 21 | 22 | let mainWindow = null; 23 | const mainWindowPromise = deferPromise(); 24 | // the http server behind the express server 25 | let frontendServerApp = null; 26 | let portPromise = IS_DEV ? Promise.resolve(3000) : findFreePort(3000); 27 | 28 | warnOnUnsupportedPlatform(); 29 | 30 | // 'app' | 'update' 31 | let appMode = 'app'; 32 | 33 | ipcMain.handle('request-app-mode', () => { 34 | console.log('app mode requested by frontend, sending: ', appMode); 35 | return appMode; 36 | }); 37 | 38 | ipcMain.handle('request-user-speakers', async (event, ...args) => { 39 | // add user speakers from `app.path('userData')/speakers/.npy`. 40 | 41 | const userDataSpeakers = []; 42 | const userDataSpeakersPath = path.join(app.getPath('userData'), 'speakers'); 43 | try { 44 | await fs.promises.access(userDataSpeakersPath); 45 | const files = await fs.promises.readdir(userDataSpeakersPath); 46 | for (const file of files) { 47 | if (file.endsWith('.npy')) { 48 | const basename = path.basename(file, '.npy'); 49 | userDataSpeakers.push({ id: basename, name: basename, user: true }); 50 | } 51 | } 52 | } catch (err) { 53 | console.error('Error accessing user data speakers path, will revert to base speakers:', err); 54 | } 55 | 56 | return userDataSpeakers; 57 | }) 58 | 59 | if (!IS_DEV || process.env.DEBUG_OTA === 'true') { 60 | try { 61 | const needsUpdate = setupUpdates({ 62 | mlServer: 'https://mv-downloads.s3.eu-west-1.amazonaws.com/mvml', 63 | mlVersion: package.config.mlVersion, 64 | }); 65 | 66 | if (needsUpdate) { 67 | // ml update, not electron 68 | appMode = 'update'; 69 | } 70 | } catch (e) { 71 | console.error('Error setting up updates, probably no internet, will continue without updates'); 72 | console.log(e); 73 | } 74 | } 75 | 76 | if (!IS_DEV || process.env.DEBUG_SHORTCUT === 'true') { 77 | try { 78 | setupShortcuts(); 79 | } catch (e) { 80 | console.error('Error setting up shortcuts'); 81 | console.log(e); 82 | } 83 | } 84 | 85 | let forceQuit = false; 86 | 87 | if (process.platform === 'darwin') { 88 | systemPreferences.askForMediaAccess('microphone') 89 | .then(granted => console.log(`Microphone access granted: ${granted}`)) 90 | .catch(error => console.log(error)) 91 | } 92 | 93 | function createWindow() { 94 | const defaultHeight = process.platform === 'darwin' ? 680 : 720; 95 | let mainWindowState = windowStateKeeper({ 96 | defaultWidth: 800, 97 | defaultHeight 98 | }); 99 | 100 | mainWindow = new BrowserWindow({ 101 | x: mainWindowState.x, 102 | y: mainWindowState.y, 103 | width: mainWindowState.defaultWidth, 104 | height: defaultHeight, 105 | resizable: IS_DEV, 106 | webPreferences: { 107 | devTools: IS_DEV, 108 | preload: path.join(__dirname, 'preload.js'), 109 | }, 110 | backgroundColor: '#232234', 111 | // hide titlebar on mac only 112 | titleBarStyle: process.platform === 'darwin' ? 'hidden' : 'default' 113 | }) 114 | 115 | mainWindow.webContents.on('will-navigate', (e, url) => { 116 | // add more as time goes on and we add more OAuth providers 117 | if (url.startsWith("https://rxhakgjibqkojyocfpjt.supabase.co/auth/v1/authorize?provider=google")) { 118 | 119 | url = url.replace("redirect_to", "old_redirect_to_not_for_oauth"); 120 | url += "&redirect_to=" + encodeURIComponent("http://localhost:" + (IS_DEV ? 3000 : (frontendServerApp?.address()?.port ?? 3000)) + "/") 121 | e.preventDefault(); 122 | shell.openExternal(url); 123 | } 124 | 125 | }) 126 | 127 | mainWindow.on('close', (e) => { 128 | if (process.platform === 'darwin' && !forceQuit) { 129 | /* the user only tried to close the window */ 130 | e.preventDefault(); 131 | mainWindow.hide(); 132 | } 133 | }); 134 | 135 | portPromise.then(port => { 136 | mainWindow.loadURL(`http://localhost:${port}/`) 137 | }); 138 | 139 | // opens URLs in the default browser 140 | mainWindow.webContents.on('new-window', function (e, url) { 141 | e.preventDefault(); 142 | shell.openExternal(url); 143 | }); 144 | // open dev tools by default in dev mode 145 | if (IS_DEV) { 146 | mainWindow.webContents.openDevTools(); 147 | } 148 | mainWindowState.manage(mainWindow); 149 | 150 | mainWindowPromise.resolve(); 151 | 152 | return mainWindow; 153 | } 154 | 155 | let pyProc = null 156 | 157 | function createPyProc() { 158 | if (IS_DEV) { 159 | pyProc = require('child_process').spawn('python', ['server/main.py']); 160 | } else { 161 | const file = path.join(path.resolve(__dirname), './dist/metavoice/metavoice'); 162 | pyProc = require('child_process').execFile(file, (error, stdout, stderr) => { 163 | if (error) { 164 | throw error; 165 | } 166 | console.log(stdout); 167 | }); 168 | } 169 | 170 | pyProc.stdout.pipe(process.stdout); 171 | pyProc.stderr.pipe(process.stderr); 172 | 173 | if (pyProc) { 174 | console.log('Child process started successfully!') 175 | } 176 | } 177 | 178 | function createFrontendServer() { 179 | const express = require('express'); 180 | const frontendApp = express(); 181 | 182 | frontendApp.use(express.static(path.join(__dirname, 'dist-react'))); 183 | 184 | portPromise.then((port) => { 185 | frontendServerApp = frontendApp.listen(port, () => { 186 | console.log(`Localhost frontend server listening at http://localhost:${port}`) 187 | }); 188 | }); 189 | } 190 | function exitFrontendServer() { 191 | if (!frontendServerApp) return Promise.resolve(); 192 | 193 | return frontendServerApp.close(); 194 | } 195 | 196 | async function exitApp() { 197 | exitFrontendServer(); 198 | 199 | if (!pyProc) return; 200 | 201 | // kill the fast api server 202 | pyProc.kill(); 203 | pyProc = null; 204 | 205 | // process.kill() doesn't issue a SIGTERM. Hence, we run the below bash command to kill all metavoice processes. 206 | // TODO sidroopdaska: understand behaviour on windows and assess if fix is needed. 207 | const exec = require('child_process').exec; 208 | if (process.platform === 'darwin') { 209 | await exec("pkill -9 'metavoice'"); 210 | } else { 211 | await exec("taskkill /f /t /im MetaVoice.exe"); 212 | } 213 | 214 | console.log('Shut down child process'); 215 | 216 | app.exit(); 217 | } 218 | 219 | function setupUpdates(obj) { 220 | const { 221 | mlServer, 222 | mlVersion, 223 | } = obj; 224 | 225 | const logs = []; 226 | const log = (msg) => { 227 | console.log(msg); 228 | logs.push({ type: 'log', msg }); 229 | mainWindow && mainWindow.webContents.send('log-info', { msg }); 230 | }; 231 | const logError = (msg, error) => { 232 | console.error(msg); 233 | console.error(error); 234 | logs.push({ type: 'error', msg, error }); 235 | mainWindow && mainWindow.webContents.send('log-error', { msg, error }); 236 | }; 237 | 238 | ipcMain.handle('request-logs', () => { 239 | return logs; 240 | }); 241 | 242 | // electron 243 | try { 244 | const alreadyInstalledNewVersionLocation = fs.readFileSync(path.join(__dirname, 'use-new-version.txt'), 'utf-8'); 245 | if (alreadyInstalledNewVersionLocation) { 246 | // prevent user from opening current app, and open the new one for them 247 | try { 248 | log('el update: new version already installed, opening it'); 249 | const newAppPath = path.join(alreadyInstalledNewVersionLocation, `MetaVoice.${process.platform === 'darwin' ? 'app' : 'exe'}`); 250 | log(`el update: new app path: ${newAppPath}`); 251 | notify({ 252 | title: 'MetaVoice update', 253 | body: `New version was installed. Opening it now...`, 254 | }) 255 | 256 | // close frontend server to free up port for new app 257 | exitFrontendServer() 258 | .then(() => { 259 | shell.openPath(newAppPath); 260 | 261 | setTimeout(() => { 262 | // if we exit right away, the new app won't have time to open 263 | app.exit(); 264 | }, 2000); 265 | }) 266 | .catch((e) => { 267 | logError('el update: new version was installed, but could not be opened due to the frontend server being uncloseable', e); 268 | }) 269 | 270 | return true; 271 | } catch (e) { 272 | logError('el update: new version was installed, but could not be opened', e); 273 | log('el update: if you think there was mistake while updating, please remove `resources/app/use-new-versbion.txt`, and restart this app. This will re-install the new version') 274 | notify({ 275 | title: 'MetaVoice update', 276 | body: `New version was installed, but could not be opened. Please open it manually at ${newAppPath}`, 277 | }) 278 | return false; 279 | } 280 | } 281 | } catch (e) { 282 | // new version wasn't installed if present 283 | } 284 | const elServer = 'https://update.electronjs.org'; 285 | const elFeed = `${elServer}/metavoicexyz/MetaVoiceLive/${process.platform}-${process.arch}/${app.getVersion()}`; 286 | 287 | log(`el update: checking for new versions at ${elFeed}`); 288 | fetch(elFeed) 289 | .then((res) => { 290 | if (res.status === 204) { 291 | return false; 292 | } 293 | return res.json(); 294 | }) 295 | .then((update) => { 296 | if (!update) { 297 | log('el update: no new versions available. Please don\'t close the window, mvml updates may be processing'); 298 | return; 299 | } 300 | 301 | const { 302 | name, 303 | notes, 304 | url: updateUrl, 305 | } = update; 306 | 307 | // download zip file to Download folder, with given name 308 | const url = new URL(updateUrl); 309 | // e.g. MetaVoice-0.0.0-win32-x64 310 | const pkgName = url.pathname.split('/').pop().split('.').slice(0, -1).join('.'); 311 | 312 | const downloadDestination = path.resolve(`${app.getPath('downloads')}/${pkgName}.zip`) 313 | const destination = path.resolve(`${app.getPath('downloads')}/${pkgName}`) 314 | 315 | notify({ 316 | title: 'MetaVoice Update', 317 | body: `New version ${name} available! Downloading in the background ...`, 318 | }) 319 | log(`el update: new version "${name}" available! Downloading from ${url} into ${downloadDestination}`); 320 | let ellipsedNotes = notes.split('\n').slice(0, 6); 321 | if (ellipsedNotes.length === 6) { 322 | ellipsedNotes[5]('...'); 323 | } 324 | ellipsedNotes = ' ' + ellipsedNotes.join(' \n'); 325 | log(`el update notes from new version:\n${ellipsedNotes}`); 326 | 327 | if (fs.existsSync(downloadDestination)) { 328 | log(`el update: file already exists at ${downloadDestination}, will remove and re-download`); 329 | fs.rmSync(downloadDestination); 330 | } 331 | 332 | const fileStream = fs.createWriteStream(downloadDestination, { flags: 'wx' }); 333 | request(updateUrl).pipe(fileStream) 334 | 335 | fileStream.on('error', () => { 336 | notify({ 337 | title: 'MetaVoice Update', 338 | body: `Error downloading new version ${name}!`, 339 | }) 340 | logError(`el update: error downloading new version "${name}"!`, e); 341 | }); 342 | 343 | fileStream.on('finish', () => { 344 | notify({ 345 | title: 'MetaVoice Update', 346 | body: `New version ${name} downloaded! Installing in the background ...`, 347 | }) 348 | log(`el update: downloaded new version "${name}"!`); 349 | 350 | // could pipe in directly from request, but this makes debugging easier, allows caching, and better progress updates for user 351 | const stream = fs.createReadStream(downloadDestination).pipe(unzipper.Extract({ path: destination })); 352 | const unzipPromise = new Promise((resolve, reject) => { 353 | stream.on('finish', resolve); 354 | stream.on('error', reject); 355 | }); 356 | unzipPromise.catch((err) => { 357 | notify({ 358 | title: 'MetaVoice Update', 359 | body: `Error installing new version ${name}!`, 360 | }) 361 | log('el update: fatal error decompressing the electron app, please report this to gm@themetavoice.xyz', err); 362 | }); 363 | 364 | const markAsOutdatedPromise = unzipPromise.then(() => { 365 | // add `use-new-version.txt` file in current folder, which will be detected on boot telling the user to use the new version 366 | const useNewVersionPath = path.resolve(`${__dirname}/use-new-version.txt`); 367 | fs.writeFileSync(useNewVersionPath, destination); 368 | log(`el update: noted new version location in ${useNewVersionPath}`); 369 | }); 370 | markAsOutdatedPromise.catch((err) => { 371 | logError('el update: error marking new version as outdated, please report this to gm@themetavoice.xyz', err); 372 | }); 373 | 374 | 375 | const _endPromise = markAsOutdatedPromise.then(() => { 376 | notify({ 377 | title: 'MetaVoice Update', 378 | body: `New version ${name} installed! Please open the executable in ${destination} to use the new version! Feel free to delete this version`, 379 | }) 380 | log(`el update: success! Please open the executable in ${destination} to use the new version! Feel free to delete this version`) 381 | }) 382 | }); 383 | }); 384 | 385 | 386 | // ml model 387 | const { needsNewVersion, reason } = checkNeedsNewVersion(mlVersion); 388 | 389 | if (needsNewVersion) { 390 | log(`mvml update: new version of ml model required! ${reason}`); 391 | 392 | // will do in a loop until it works 393 | updateMvml({ 394 | mlVersion, 395 | mlServer, 396 | log, 397 | logError, 398 | retriesLeft: 10, 399 | }); 400 | } 401 | 402 | return needsNewVersion; 403 | } 404 | 405 | function setupShortcuts() { 406 | if (appMode === 'update') { 407 | console.log('shortcut: skipping shortcut setup in update mode'); 408 | return; 409 | } 410 | if (process.platform !== 'win32') return; 411 | 412 | // add a shortcut icon to user's desktop pointing to the executable 413 | const shortcutPath = path.resolve(`${app.getPath('desktop')}/MetaVoice Live.lnk`); 414 | const exePath = path.resolve(`${__dirname}/../../MetaVoice.exe`); 415 | const shortcutOpts = { 416 | target: exePath, 417 | description: "MetaVoice Live", 418 | // TODO icon? Need to bundle properly in exe 419 | } 420 | let success = false; 421 | if (!fs.existsSync(shortcutPath)) { 422 | // create the shortcut 423 | console.log(`shortcut: creating shortcut at ${shortcutPath} to ${exePath}`); 424 | success = shell.writeShortcutLink(shortcutPath, 'create', shortcutOpts) 425 | } else { 426 | // update the shortcut to point to the the current exe 427 | console.log(`shortcut: updating shortcut at ${shortcutPath} to point to ${exePath}`); 428 | success = shell.writeShortcutLink(shortcutPath, 'update', shortcutOpts) 429 | } 430 | 431 | if (!success) { 432 | console.error('shortcut: error'); 433 | } 434 | } 435 | 436 | function handleCustomProtocol(url) { 437 | // mainwindow not instantiated yet 438 | if (!mainWindow) return; 439 | 440 | // we only want the tokens stored in the hash, the rest of the url can be ignored 441 | const hash = url.replace(/^.+#/, "#"); 442 | 443 | const port = IS_DEV ? 3000 : (frontendServerApp?.address()?.port ?? 3000); 444 | const internalUrl = `http://localhost:${port}/${hash}`; 445 | 446 | mainWindow.loadURL(internalUrl); 447 | setTimeout(() => { 448 | // reload page so supabase knows to use the hash tokens 449 | mainWindow.reload(); 450 | // but wait so the page can receive the hash 451 | }, 1000) 452 | } 453 | 454 | // remove so we can register each time as we run the app. 455 | app.removeAsDefaultProtocolClient("app"); 456 | var didProtocolSucceed; 457 | // If we are running a non-packaged version of the app && on windows 458 | if ( 459 | (process.env.NODE_ENV === "development" && process.platform === "win32") || 460 | (process.defaultApp && process.argv.length >= 2) 461 | ) { 462 | // Set the path of electron.exe and your app. 463 | // These two additional parameters are only available on windows. 464 | didProtocolSucceed = app.setAsDefaultProtocolClient( 465 | "metavoice", 466 | process.execPath, 467 | [path.resolve(process.argv[1])] 468 | ); 469 | } else { 470 | //TODO On macOS and Linux, this feature will only work when your app is packaged. It will not work when you're launching it in development from the command-line. When you package your app you'll need to make sure the macOS Info.plist and the Linux .desktop files for the app are updated to include the new protocol handler. Some of the Electron tools for bundling and distributing apps handle this for you. 471 | didProtocolSucceed = app.setAsDefaultProtocolClient("metavoice"); 472 | } 473 | //TODO (this is not a TODO, its to highlight that below is to handle custom protocol for MACOS) 474 | app.on("open-url", (event, url) => { 475 | event.preventDefault(); 476 | // handle the data 477 | handleCustomProtocol(url); 478 | }); 479 | const gotTheLock = app.requestSingleInstanceLock(); 480 | 481 | if (!gotTheLock) { 482 | app.quit(); 483 | } else { 484 | //TODO (this is not a TODO, its to highlight that below is to handle custom protocol for WINDOWS & LINUX) 485 | app.on("second-instance", (event, commandLine, workingDirectory) => { 486 | // Someone tried to run a second instance, we should focus our window. 487 | if (mainWindow) { 488 | if (mainWindow.isMinimized()) mainWindow.restore(); 489 | mainWindow.focus(); 490 | } 491 | // the commandLine is array of strings in which last element is deep link url 492 | handleCustomProtocol(commandLine.at(commandLine.length - 1)); 493 | }); 494 | 495 | // Create mainWindow, load the rest of the app, etc... 496 | 497 | app.whenReady().then(() => { 498 | if (appMode === "app") { 499 | createPyProc(); 500 | } 501 | if (!IS_DEV) { 502 | createFrontendServer(); 503 | } 504 | const window = createWindow(); 505 | protocol.handle("metavoice", (request) => { 506 | handleCustomProtocol(request.url); 507 | }); 508 | app.on("activate", () => mainWindow.show()); 509 | 510 | // workaround for email+password sign-in: supabase gets the token, but no hash is set, 511 | // so no hash is detected, so the user is not logged in. But refreshing the page fixes it. 512 | const SUPABASE_URL = 'https://rxhakgjibqkojyocfpjt.supabase.co/auth/v1/token?*' 513 | session.defaultSession.webRequest.onCompleted({ urls: [SUPABASE_URL] }, (details) => { 514 | // only reload if auth succeeded, otherwise no error message would be shown 515 | if (details.statusCode === 200) { 516 | // wait for supabase to set internals correctly 517 | setTimeout(() => { 518 | mainWindow.reload(); 519 | }, 500) 520 | } 521 | }); 522 | }); 523 | } 524 | 525 | // Quit when all windows are closed, except on macOS. There, it's common 526 | // for applications and their menu bar to stay active until the user quits 527 | // explicitly with Cmd + Q. 528 | app.on('window-all-closed', function () { 529 | if (process.platform !== 'darwin') app.quit() 530 | }) 531 | 532 | app.on('will-quit', exitApp) 533 | 534 | app.on('before-quit', () => forceQuit = true); 535 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------