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 |
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 |
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 | [](https://twitter.com/metavoiceio)
5 | 
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 |
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 |
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 |
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 |
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 | .
--------------------------------------------------------------------------------