Skip to content

Commit

Permalink
Merge ae6ba2d into 969a3b7
Browse files Browse the repository at this point in the history
  • Loading branch information
urinieto committed Jan 26, 2017
2 parents 969a3b7 + ae6ba2d commit d78e2c4
Showing 1 changed file with 68 additions and 12 deletions.
80 changes: 68 additions & 12 deletions scripts/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"""
from __future__ import print_function

import argparse
from builtins import input
import logging
import os
import requests
from requests.packages.urllib3.util.retry import Retry
Expand All @@ -23,43 +25,97 @@

HTTP_SERVER = {2: 'SimpleHTTPServer',
3: 'http.server'}[sys.version_info.major]
WEBAPP_PORT = 8000
SERVER_PORT = 8080


def kill(*proccesses):
"""Kills a list of processes.
Parameters
----------
processes: list
List of process ids to be killed.
"""
for proc in proccesses:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)


def run():
server = subprocess.Popen(['python', 'backend_server/main.py', '--port',
'8080', '--local', '--debug'],
stdout=subprocess.PIPE, preexec_fn=os.setsid)
def run(wport, sport):
"""Main process to run the demo.
Parameters
----------
wport: int
Webapp port number.
sport: int
Server port number.
"""
# Some sanity checks
assert os.path.isdir("docs") and os.path.isdir("backend_server"), \
"This script must be launched from OpenMic's root directory."
assert os.path.isdir("audio-annotator"), \
"Audio Annotator not found: please run:\n\t" \
"git submodule update --init"

# Run the server
cmd = "python {} --port {} --local {}".format(
os.path.join('backend_server', 'main.py'), sport, '--debug')
server = subprocess.Popen(cmd.split(" "), stdout=subprocess.PIPE,
preexec_fn=os.setsid)

# Test that the server is on; will raise an exception after enough attempts
session = requests.Session()
adapter = HTTPAdapter(max_retries=Retry(total=8, backoff_factor=0.1))
session.mount('http://', adapter)
try:
session.get('http://localhost:8080')
session.get('http://localhost:{}'.format(sport))
except requests.exceptions.ConnectionError:
kill(server)
raise EnvironmentError(
"Unable to confirm that the server started successfully.")

# Upload audio to the server
fnames = ["267508__mickleness__3nf.ogg",
"345515__furbyguy__strings-piano.ogg"]
for fn in fnames:
fpath = os.path.abspath("./data/audio/{}".format(fn))
requests.post('http://localhost:8080/api/v0.1/audio',
fpath = os.path.abspath(os.path.join('data', 'audio', fn))
requests.post('http://localhost:{}/api/v0.1/audio'.format(sport),
files=dict(audio=open(fpath, 'rb')))

webapp = subprocess.Popen(['python', '-m', HTTP_SERVER],
# Run the webapp
webapp = subprocess.Popen(['python', '-m', HTTP_SERVER, str(wport)],
stdout=subprocess.PIPE, preexec_fn=os.setsid)

print("Now serving at: http://localhost:8000/docs/annotator.html")
input("Press return to exit.")
logging.info("Now serving at: http://localhost:{}"
"/docs/annotator.html".format(wport))
try:
input("Press return to exit.\n")
except KeyboardInterrupt:
# Capturing Ctrl-C, to make sure we always shutdown the server
pass
logging.info("Shutting down server")
kill(server, webapp)


if __name__ == '__main__':
run()
parser = argparse.ArgumentParser(
description="Run a local demo of the server-annotator system.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-p",
dest="wport",
default=WEBAPP_PORT,
type=int,
help="WebApp port number")
parser.add_argument("-sp",
dest="sport",
default=SERVER_PORT,
type=int,
help="Server port number")
args = parser.parse_args()

# Setup the logger
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',
level=logging.INFO)

# Call main process
run(args.wport, args.sport)

0 comments on commit d78e2c4

Please sign in to comment.