{"id":21930737,"url":"https://github.com/previsionio/prevision-dash-app","last_synced_at":"2025-03-22T12:48:57.260Z","repository":{"id":86604778,"uuid":"447220515","full_name":"previsionio/prevision-dash-app","owner":"previsionio","description":null,"archived":false,"fork":false,"pushed_at":"2022-01-20T08:35:20.000Z","size":271,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-01-27T12:21:17.705Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/previsionio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-12T13:03:59.000Z","updated_at":"2022-01-19T15:42:36.000Z","dependencies_parsed_at":null,"dependency_job_id":"3d27f04c-8f0c-41be-9372-b683724a0686","html_url":"https://github.com/previsionio/prevision-dash-app","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/previsionio%2Fprevision-dash-app","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/previsionio%2Fprevision-dash-app/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/previsionio%2Fprevision-dash-app/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/previsionio%2Fprevision-dash-app/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/previsionio","download_url":"https://codeload.github.com/previsionio/prevision-dash-app/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244959442,"owners_count":20538626,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-28T23:11:15.403Z","updated_at":"2025-03-22T12:48:57.229Z","avatar_url":"https://github.com/previsionio.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# prevision-dash-app\n\nDash, and plotly, are perfect candidate for exposing models and predictions to the world. In this guide, I am showing you how to deploy a Dash project that use a Prevision Model into Previsio Studio.\n\nWe are building a very simple app that :\n\n- call a multiclass model with a text input\n- get the result and diplay the probability of each class as a bar chart\n\n## Prerequiste\n\nYou need a git repo to deploy your app\n\n## Project architecture\n\nYou can clone this project to get a boilerplate :\n\n`git clone https://github.com/previsionio/prevision-dash-app.git`\n\nand inspect the project folder tree. \n\n### Required \n\nIn order to deploy your project to Prevision.io platform you **must** have :\n- a requirements.txt file ( with all your requirements obviously) at the root of the projects\n- a `run.py` file , at the root too\n\n### Advised \n\nA simple but efficient folder structure is :\n\n- a service folder, with all your api call ( and a model.py file for calling  prevision model )\n- an asset folder with your css ( for example `layout.css` and `styles.css` )\n\n\n## Setup\n\nIn order to create a dev environnement to code and test your application :\n\n\n- create a virtual env\n- activate it ̀\n- install requirements\n    - pandas\n    - plotly-express\n    - dash\n    - gunicorn\n- fill the .env file with your model url, id and secret ( get it on [the deployed model page](https://previsionio-previsionio.readthedocs-hosted.com/en/latest/studio/deployments/index.html#inspect-and-monitor-a-deployed-experiment) )\n- launch the app with gunicorn\n\n\n```\ngit clone https://github.com/previsionio/prevision-dash-app.git\ncd prevision-dash-app\npython -m venv env\nsource env/bin/activate\npip install -r requirements.txt \ngunicorn --bind 0.0.0.0:8080  --threads 10 -w 2 --timeout 120 --limit-request-line 0 --access-logfile - run:app\n```\n\nIf everything works fine, you could open (http://localhost:8080) with yoour browser and you should see a simple interactive dashboard\n\n\n![img](img/homepage.png)\n\n### Warning\n\nYour app must work the following option :\n\n`gunicorn --bind 0.0.0.0:8080  --threads 10 -w 2 --timeout 120 --limit-request-line 0 --access-logfile - run:app`\n\n(*if you work on windows setup you can use waitress server instead*)\n\nCheck that you \"main\" file is named `run.py` and that the dash app server is bind to the app variable :\n\n```\ndashboard = dash.Dash(__name__) \napp = dashboard.server\n```\n\nMoreover, you should try your app with the -w 2 option to be sure that it is truly stateless and can run in many thread.\n\n## Calling the model\n\nIf you want to use a Model hosted on prevision platform, you need to initialize a request-oauthlib client. Do it in the `services/model`file.\n\nYou should have your credentials in a .env file \n\n```python\n\nload_dotenv()\nclient_id = os.getenv('client_id')\nclient_secret = os.getenv('client_secret')\nmodel_url = os.getenv('model_url')\n\nclient = BackendApplicationClient(client_id=client_id)\n\n```\n\nThen write a function that send the form data as a `POST` request json payload. Here the model has only one feature, `text` but you need to change this accordong to your model feature\n\n```python\ndef send(text):\n\n    try:\n        predict_url = f\"{model_url}/predict\"\n\n        payload = json.dumps({\n            \"text\": text\n        })\n        headers = {'Content-Type': 'application/json'}\n\n        oauth = OAuth2Session(client=client)\n        oauth.fetch_token(\n            token_url=\n            'https://accounts.prevision.io/auth/realms/prevision.io/protocol/openid-connect/token',\n            client_id=client_id,\n            client_secret=client_secret)\n\n        prediction = oauth.post(predict_url, headers=headers, data=payload)\n        res = prediction\n        data=res.json()\n\n        # You can transform the response to help the client\n        pred = transformres(data)\n        \n        return pred\n    except ConnectionError:\n        logging.error(\"Cannot call model\")\n        return {}\n```\n\n## Building the Dashboard\n\nThe dashboard is a basic interactive app  with a form and a chart. When submit button event is triggererd, the state of the form is send to the model and the response is use to update chart data \n\n```python\n# Initialise the app \ndashboard = dash.Dash(__name__) \n\n# just  a test\ndefault_text=\"j'aime la France\"\nres = model.predict_query(default_text)\nprint(res)\n\ndf = pd.DataFrame({\n    \"Candidates\": [candidate[\"name\"] for candidate in res[\"predictions\"]],\n    \"Similarity\": [candidate[\"similarity\"] for candidate in res[\"predictions\"]],\n\n})\n\n# Define the app Layout here\ndashboard.title = 'Analytics Dashboard'\n\nfig = px.bar(df, x=\"Candidates\", y=\"Similarity\", barmode=\"group\")\n\nform = html.Div([\n    html.H3(\"Texte prononcé\"),\n    html.Div([\n        \"Texte: \",\n        dcc.Textarea(id='src-txt', value=default_text  )\n    ]),\n    html.Button('Submit', id='submit-val', n_clicks=0)    \n\n])\n\npanelling = html.Div([html.Main(children= [form]), html.Aside(children=    dcc.Graph(\n        id='barchart',\n        figure=fig\n    ),)], className='vertical-panelling')\n\n\n\n\ndashboard.layout = html.Div(children=[\n    html.Header(children=html.H1(children = 'Prevision.io')),\n    panelling,\n    html.Footer(children=\"Copyright\")\n], id=\"container\")\n\n\n# A callback that listn to form submit and call the model\ndef init_callbacks(dash_app):\n    @dashboard.callback(\n    Output('barchart', 'figure'),\n    Input('submit-val', 'n_clicks'),\n    State('src-txt', 'value')    \n    )\n    def update_graph(n_clicks, value):\n        res = model.predict_query(value)\n        df = pd.DataFrame({\n            \"Candidates\": [candidate[\"name\"] for candidate in res[\"predictions\"]],\n            \"Similarity\": [candidate[\"similarity\"] for candidate in res[\"predictions\"]],\n\n        })\n        fig = px.bar(df, x=\"Candidates\", y=\"Similarity\")\n        fig.update_layout(transition_duration=500)\n        return fig\n\n\ninit_callbacks(dashboard)\napp = dashboard.server\n```\n\n## Deploying the app in prevision env\n\nOnce everything works locally, put your code into your repo. \n\nYou need to give authorization to Prevision.io platform.  Connect to Prevision.io and go to `profile \u003e federated identity`. add you gitlab or github repo then :\n\n\nGo to `Deployments \u003e Deployment applications`. Click 'create application'\n\n![img](img/new_app.png)\n\nFill the form. Plotly is a python framework so choose `python` as programming language. Select your repo and folder\n![img](img/setup1.png)\n\nDo not forget to create 3 env variable and fill them with your credentials ( or more if you add some to your project)\n![img](img/setup_2.png)\n\n\nClick Deploy button and wait. Your application should be available in a few minutes, to the url provided in the interface. If something failed, error logs are available in the `log`tab of the deployment page.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprevisionio%2Fprevision-dash-app","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fprevisionio%2Fprevision-dash-app","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprevisionio%2Fprevision-dash-app/lists"}