Search code examples
pythonhtmlpyscript

line 25 SyntaxError: 'await' outside function Pyscript


I was given a task to build a project that perform linear regression prediction using PyScript so I utilized scikit-learn with help of Javascript and panel in order to do that. Here's my full code:

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Linear Regression Predict</title>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css"/>
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>

    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vega@5"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vega-lite@5"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vega-embed@6"></script>
    <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.9.3/dist/js/tabulator.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/@holoviz/panel@0.13.0/dist/panel.min.js"></script>
    <script type="text/javascript">
      Bokeh.set_log_level("info");
        </script>

    <py-env>
        - numpy 
        - pandas
        - scikit-learn
        - panel==0.13.1a2
    </py-env>

</head>
<body style="background-color:rgb(255, 255, 255)">
    <h1>Upload CSV</h1>

      <div id="fileinput"></div>
      <div id="upload"></div>
      <div id="to_prdict"></div>
      <div id="op"></div>

      <p id="regression-op"></p>

    <py-script>

import pandas as pd 
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from panel.io.pyodide import show
import numpy as np
import panel as pn

fileInput = pn.widgets.FileInput(accept=".csv")
uploadButton = pn.widgets.Button(name="Show Prediction",button_type='primary')
to_pred = pn.widgets.Spinner(name="Total Installs",value=500,step=50,start=50)

def process_file(event):
    if fileInput.value is not None:
      data = pd.read_csv(io.BytesIO(fileInput.value))
      x = data[['High']]
      y = data[['Volume']]
    
      lr = LinearRegression()
      lr.fit(x,y)
      y_hat = lr.predict(np.array(to_pred.value).reshape(1,-1))
      
      reg_op = Element('regression-op')
      reg_op.write(y_hat)

await show(fileInput,'fileinput')
await show(uploadButton,'upload')
await show(to_pred,'to_predict')
uploadButton.on_click(process_file)
        
    </py-script>
</body>
</html>

When I checks the website this error displays:

JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 428, in eval_code .compile() File "/lib/python3.10/site-packages/_pyodide/_base.py", line 249, in compile self._gen.send(self.ast) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 158, in _parse_and_compile_gen return compile(mod, filename, mode, flags=flags) File "", line 25 SyntaxError: 'await' outside function )

I'm not sure what to cause this error because I see no error in my syntax.


Solution

  • Your have multiple problems with your code.

    1) Import asyncio

    This package is required for PyScript applications that use async functions.

    import asyncio
    

    2) Calling Async functions

    Your code is using the await with in a function that is not declared async. Change your code:

    async def init():
            uploadButton.on_click(process_file)
            await show(fileInput,'fileinput')
            await show(uploadButton,'upload')
            await show(to_pred,'to_predict')
    
    init()
    

    3) Undefined element

    Your code is referencing an undefined element to_predict. I am not sure that that is, but you will need to add that element to your code.

    await show(to_pred,'to_predict')