Skip to content

Commit

Permalink
Add a send_command GET request handler for handling requests sent in …
Browse files Browse the repository at this point in the history
…internal colab.
  • Loading branch information
jinjingforever committed Sep 27, 2024
1 parent 256de27 commit 93d9f1b
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/server/package/src/model_explorer/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ def _js(script):
display.display(display.Javascript(script))


def _is_internal_colab() -> bool:
return (
"BORG_TASK_HANDLE" in os.environ
or "X20_HOME" in os.environ
or "UNITTEST_ON_BORG" in os.environ
or "google3.research.colab.lib" in sys.modules
)


def start(
host=DEFAULT_HOST,
port=DEFAULT_PORT,
Expand Down Expand Up @@ -203,6 +212,7 @@ def start(

# Check whether it is running in colab.
colab = 'google.colab' in sys.modules or os.getenv('COLAB_RELEASE_TAG')
internal_colab = _is_internal_colab()

# Check port in non-colab environment.
if not colab:
Expand Down Expand Up @@ -277,10 +287,20 @@ def upload_file():
f.save(file_path)
return _make_json_response({'path': file_path})

# Note: using "/api/..." for POST requests is not allowed when running in
# colab.
@app.route('/apipost/v1/send_command', methods=['POST'])
@app.route('/api/v1/send_command')
def send_command():
cmd_json = json.loads(request.args.get('json', '{}'))
try:
resp = extension_manager.run_cmd(cmd_json)
return _make_json_response(resp)
except Exception as err:
traceback.print_exc()
return _make_json_response({'error': f'{type(err).__name__}: {str(err)}'})
finally:
extension_manager.cleanup(cmd_json)

@app.route('/apipost/v1/send_command', methods=['POST'])
def send_command_post():
try:
resp = extension_manager.run_cmd(request.json)
return _make_json_response(resp)
Expand Down Expand Up @@ -464,6 +484,9 @@ def embed_in_colab():
if ('%DATA_PARAM%' !== '') {
url += '&%DATA_PARAM%';
}
if ('%INTERNAL%' === 'True') {
url += '&internal_colab=1';
}
const iframe = document.createElement('iframe');
iframe.src = url;
iframe.setAttribute('width', '100%');
Expand All @@ -479,6 +502,7 @@ def embed_in_colab():
replacements = [
('%PORT%', f'{colab_port}'),
('%HOSTED_RUNTIME%', f'{colab}'),
('%INTERNAL%', f'{internal_colab}'),
('%HEIGHT%', f'{colab_height}'),
('%DATA_PARAM%', f'{data_param}'),
]
Expand Down

0 comments on commit 93d9f1b

Please sign in to comment.